2016-05-14 4 views
0

GTK3:ボタンは、私は背景が黒くすると2つのラベルがそれに応じて色を変更する必要がありたいトグルされたときGtkButtonで2人の子供をその状態に応じて違うスタイルにすることは可能ですか?

[name_label (black) value_label (grey)] - button inactive (white background) 

[name_label (white) value_label (yellow)] - button active (black background) 

:私はこのような(HBoxの経由)GtkButtonで2つのGtkLabelのウィジェットを持っています。

これはCSSでのみ可能ですか?

これは私が試したものです:

from gi.repository import Gtk, Gdk 

window = Gtk.Window() 
button = Gtk.Button() 
hbox = Gtk.HBox() 
name = Gtk.Label('Name') 
value = Gtk.Label('Value') 
value.set_name('value') 
hbox.set_spacing(10) 
hbox.pack_start(name, expand=False, fill=True, padding=0) 
hbox.pack_start(value, expand=False, fill=True, padding=0) 
button.add(hbox) 
window.add(button) 

window.connect('destroy', Gtk.main_quit) 
window.show_all() 

screen = Gdk.Screen.get_default() 
css_provider = Gtk.CssProvider() 
css_provider.load_from_path('style.css') 

context = Gtk.StyleContext() 
context.add_provider_for_screen(screen, css_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER) 

Gtk.main() 

のstyle.css:

.button { 
    background-color: white; 
    background-image: none; 
} 

.button #value { 
    color: grey; 
} 

.button:active { 
    background-color: black; 
    background-image: none; 
    color: white; 
} 

.button:active #value { 
    color: yellow; 
} 

ボタンが押されたときに値ラベルはグレーのままなので、最後のセクションは適用されません。これは期待されるものですか?

答えて

0

これで、値ラベルにクラスを動的に追加することで、これを動作させることができます。元の質問は残っています:それはCSSだけを使って行うことができますか?

EDIT: GTK3の新しいバージョンでは、次のようになります。 3.18.9(Ubuntu Xenialに含まれているもの)、CSS専用のソリューションは期待通りに機能します!

旧バージョンのGTKを使用している人には、古いソリューションを残しておきます。

from gi.repository import Gtk, Gdk 

window = Gtk.Window() 
button = Gtk.Button() 
hbox = Gtk.HBox() 
name = Gtk.Label('Name') 
value = Gtk.Label('Value') 
value.set_name('value') 
hbox.set_spacing(10) 
hbox.pack_start(name, expand=False, fill=True, padding=0) 
hbox.pack_start(value, expand=False, fill=True, padding=0) 
button.add(hbox) 
window.add(button) 

window.connect('destroy', Gtk.main_quit) 
window.show_all() 

screen = Gdk.Screen.get_default() 
css_provider = Gtk.CssProvider() 
css_provider.load_from_path('style.css') 

context = Gtk.StyleContext() 
context.add_provider_for_screen(screen, css_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER) 

ctx = value.get_style_context() 

def active(widget): 
    ctx.add_class('active_value') 

def inactive(widget): 
    ctx.remove_class('active_value') 

button.connect('pressed', active) 
button.connect('released', inactive) 
Gtk.main() 

と、対応するCSS:

.button { 
    background-color: white; 
    background-image: none; 
} 

.button #value { 
    color: gray; 
} 

.button #value.active_value { /* value label when the button is pressed */ 
    color:yellow; 
} 

.button:active { 
    background-color: black; 
    background-image: none; 
    color: white; 
} 
関連する問題