我是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;
}
&#13;
GtkStyleContext *context;
context = gtk_widget_get_style_context (GTK_WIDGET (b1));
gtk_style_context_add_class (context, "myButton");
来自here,但在运行应用时遇到错误:
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");
任何帮助表示赞赏:)
答案 0 :(得分:0)
您正在混合GTK+和gtkmm(GTK +的C ++接口)。 b1
不是GtkButton,而是Gtk::Button。
Glib::RefPtr<StyleContext> context = b1->get_style_context();
context->add_class("myButton");