Home > Net >  How to set cursor color in Gtk3 selectable label?
How to set cursor color in Gtk3 selectable label?

Time:09-17

I have a program that I've written in Perl using Gtk3 where I've created a selectable Label that I want the user to be able to copy from. By default, Gtk3 seems to assume that the user would want to select with the keyboard, so it shows a cursor / caret whenever you click on the label. Is there a way I could change the color of the cursor to something less noticeable or make it completely invisible, like what happens normally e.g. in Firefox for non-entry fields?

I saw a similar question here from 4 years back where somebody suggested using override_cursor or set_style but now with Gtk 3.24 both seem to be deprecated. I tried defining a CSS style with a custom caret-color property but it seems to be working only for Entry widgets and not for selectable Labels. I get that behavior whether I define the custom caret color for all classes * or just for label. Other CSS properties, such as background-color seem to work fine.

A bonus question: Gtk3 reference manual suggests using a value between GTK_STYLE_PROVIDER_PRIORITY_FALLBACK and GTK_STYLE_PROVIDER_PRIORITY_USER for the second argument of add_provider. How do I write these constants in Perl? I've tried GTK_STYLE_PROVIDER_PRIORITY_FALLBACK with and without quotes, "style-provider-priority-fallback", "priority-fallback" and a number of other combinations but none seem to be recognized by Perl.

Here is the relevant part of my code this far:

#!/usr/bin/perl
use Gtk3 -init;

my $window = Gtk3::Window->new('toplevel');
my $box = Gtk3::Box->new('horizontal',0);

my $label = Gtk3::Label->new();
$label->set_selectable(TRUE);
$label->set_label("Testing");

$box->pack_start($label, FALSE, FALSE, 5);

my $style = "* { caret-color: transparent; }";
my $css = Gtk3::CssProvider->new();
$css->load_from_data($style);

my $stylecontext = $label->get_style_context();
$stylecontext->add_provider($css,1);

$window->add($box);
$window->show_all;

Gtk3->main();

CodePudding user response:

You can add a custom class to your label using gtk_style_context_add_class(). For example:

use strict;
use warnings;
use Glib qw(TRUE FALSE);
use Gtk3 -init;

my $window = Gtk3::Window->new('toplevel');
$window->signal_connect( destroy  => sub { Gtk3->main_quit() } );
my $box = Gtk3::Box->new('horizontal',0);
my $label = Gtk3::Label->new();
$label->set_selectable(TRUE);
$label->set_label("Testing");
$box->pack_start($label, FALSE, FALSE, 5);
my $stylecontext = $label->get_style_context();
$stylecontext->add_class("my_label");
my $style = ".my_label { caret-color: transparent; }";
my $css = Gtk3::CssProvider->new();
$css->load_from_data($style);
$stylecontext->add_provider($css, Gtk3::STYLE_PROVIDER_PRIORITY_USER);
$window->add($box);
$window->show_all;
Gtk3->main();

This also shows how to obtain the value of the constant GTK_STYLE_PROVIDER_PRIORITY_USER.

  • Related