我是 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");
从这里开始,但在运行应用程序时出错:
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");
从这里 但得到编译错误:
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");
任何帮助表示赞赏:)