如何在 Linux 上为 c++ 中的 gtkmm3 中的特定按钮设置 CSS class

How to set CSS class for specific button in gtkmm3 in c++ on Linux

我是 Linux 编程新手。 最近我开始学习 gtkmm3 来为我的研究项目制作 GUI,但我一直卡在这个问题上。 我有几个按钮,它们的样式是 CSS 文件,我想为选定的按钮设置其他样式,但没有任何效果。 这就是我制作按钮和阅读 CSS 文件的方式:

Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv);
Gtk::Window window;
window.set_default_size(800, 480);

Glib::RefPtr<Gtk::CssProvider> cssProvider = Gtk::CssProvider::create();
cssProvider->load_from_path("style.css");   
Glib::RefPtr<Gtk::StyleContext> styleContext = Gtk::StyleContext::create();
Glib::RefPtr<Gdk::Screen> screen = Gdk::Screen::get_default();//get default screen
styleContext->add_provider_for_screen(screen, cssProvider, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);//add provider for screen in all application

Gtk::Box *vbox = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_VERTICAL, 0));
window.add(*vbox); 

Gtk::Button *b1 = new Gtk::Button("b1");
b1->signal_clicked().connect(sigc::ptr_fun(&on_b1_click));

Gtk::Button *b2 = new Gtk::Button("b2");
b2->signal_clicked().connect(sigc::ptr_fun(&on_b1_click));

vbox->add(*b1);
vbox->add(*b2);        

和CSS文件:

.button {
 color: red;
 background: red;
 border-color: red;
}
.button:hover { 
 color: yellow;
    background-color: yellow;
 border-color: yellow;
}
.myButton{
 color: red;
 background: blue;
 border-color: red;
}
我尝试像这样为按钮设置其他样式:

GtkStyleContext *context;
context = gtk_widget_get_style_context (GTK_WIDGET (b1));
gtk_style_context_add_class (context, "myButton");

来自 ,但在 运行 app:

时出现错误
GLib-GObject-WARNING **: invalid cast from '(null)' to 'GtkWidget'
Gtk-CRITICAL **: gtk_widget_get_style_context: assertion 'GTK_IS_WIDGET (widget)' failed
Gtk-CRITICAL **: gtk_style_context_add_class: assertion 'GTK_IS_STYLE_CONTEXT (context)' failed

gtk_widget_set_name (b1, "myButton");

来自 here 但出现编译错误:

main.cpp: In function ‘int main(int, char**)’: main.cpp:34:40: error: cannot convert ‘Gtk::Button*’ to ‘GtkWidget* {aka _GtkWidget*}’ for argument ‘1’ to ‘void gtk_widget_set_name(GtkWidget*, const gchar*)’
 gtk_widget_set_name (b1, "myButton");

感谢任何帮助:)

您正在混合GTK+ with gtkmm (C++ interface for GTK+). b1 is not a GtkButton but Gtk::Button

使用Gtk::StyleContext:

Glib::RefPtr<StyleContext> context = b1->get_style_context();
context->add_class("myButton");