我是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");
任何帮助:)
您将GTK 与GTKMM(GTK 的C 接口)混合。 b1
不是gtkbutton,而是gtk :: button。
使用GTK :: StyleContext:
Glib::RefPtr<StyleContext> context = b1->get_style_context();
context->add_class("myButton");