gtkgjs

Styling GTK widget with CssProvider ... set_name doesnt work


I set the name of buttonA to "ButtonA" but cant reach it in the css file with css selector: #buttonA, whats wrong=? and i cant set the border of a button, only for label, and for label i cant set the background-color inside the button, i only can set a background-image I use GTK 3

#!/usr/bin/gjs
const Gtk = imports.gi.Gtk;
const Gdk = imports.gi.Gdk;

Gtk.init(null);

const window = new Gtk.Window();

const box=new Gtk.Box ({orientation:1}),
      buttonA=new Gtk.Button ({label:"A"}),
      buttonB=new Gtk.Button ({label:"B"}),
      buttonC=new Gtk.Button ({label:"C"}),
      display=Gdk.Display.get_default (),
      screen=display.get_default_screen(),
      provider= new Gtk.CssProvider();

provider.load_from_path('test.css');
Gtk.StyleContext.add_provider_for_screen(screen,provider,0);

buttonA.set_name("buttonA");
buttonB.set_name("buttonB");
buttonC.set_name("buttonC");

box.add(buttonA);
box.add(buttonB);
box.add(buttonC);

window.add(box);
window.set_title("CSS Example");
window.connect('destroy', () => { Gtk.main_quit(); });
window.set_size_request(640, 480);
window.show_all();
Gtk.main();

the test.css file:

button {font-family:Arial; font-size:20px;}
button > label {border-radius:10px; border: 1px solid black; background-color:orange;}
#buttonA {font-size:60px;}

Solution

  • If you set the name property at construct-time, or possibly just before applying the CSS provider, it seems to work correctly:

    const buttonA = new Gtk.Button({
      label: 'A',
      name: 'buttonA',
    });