Search code examples
rubygtk3

Ruby GTK3 how do I change the application theme?


I am writing a simple app to display my GTK3 theme:

#!/usr/bin/ruby -W0
require 'gtk3'

app = Gtk::Application.new('org.xfce-colour.example', :flags_none)

app.signal_connect('activate') do |a|
    w = Gtk::ApplicationWindow.new(a)
    w.set_title('XFCE Colour')
    w.set_icon('/home/sourav/Documents/xfce_colour.png')
    w.set_default_size(70, 70)

    g = Gtk::Grid.new
    w.add(g)

    b1 = Gtk::Button.new(label: 'Button')
    g.attach(b1, 0, 0, 1, 1)

    b2 = Gtk::CheckButton.new('')
    g.attach(b2, 1, 0, 1, 1)

    b3 = Gtk::RadioButton.new('')
    g.attach(b3, 2, 0, 1, 1)

    b4 = Gtk::SearchEntry.new()
    g.attach(b4, 3, 0, 1, 1)

    b5 = Gtk::ToggleButton.new('Button')
    g.attach(b5, 0, 1, 1, 1)

    b6 = Gtk::ColorButton.new
    g.attach(b6, 1, 1, 1, 1)

    b7 = Gtk::Switch.new
    g.attach(b7, 2, 1, 1, 1)

    b8 = Gtk::Entry.new()
    g.attach(b8, 3, 1, 1, 1)

    [b1, b2, b3, b4, b5, b6, b7, b8].each do |b|
        begin
            b.margin = 6
        rescue Exception
            puts $!
        end
    end

    w.show_all
end

app.run

Please comment the w.set_icon('...') line before running.


What I want to do is changing the GTK theme from the app as it's done in A Widget Factory.

For example, I would be able to send the first argument my theme name:

ruby layout.rb XFCE_Colour_Lite_Pink

And set the theme to XFCE_Colour_Lite_Pink: Preview

I am using XFCE4, and it will be better if I can even change the WM theme.


Edit: As stated here, in Python, we have the Gtk.set_property() method. I followed this for Ruby:

settings = Gtk::Settings.new
puts settings.set_property('XFCE_Colour_Lite_Yellow', 'Papirus')

I got the error:

Traceback (most recent call last):
    1: from layout.rb:7:in `<main>'
layout.rb:7:in `set_property': No such property: XFCE_Colour_Lite_Yellow (GLib::NoPropertyError)

Solution

  • After looking up the source code for AWF, I managed to change the theme by adding:

    Gtk::Settings.default.set_gtk_theme_name ARGV[0] if ARGV[0]
    

    If the ARGV[0] is not a theme name, it will use the default theme.

    There are other methods, for example:

    Gtk::Settings.default.gtk_application_prefer_dark_theme = true
    

    To enable dark theme. I Used Gtk::Settings.default.methods.sort to sort the methods as the current ri documentation doesn't cover anything apart from licence information.