文章目录
前言
- 程序样式和代码逻辑分离开 使代码逻辑更可观
css选择器
-
Cambalache提供了两种
-
css-classes 相当于css里的类名:class="类名"
-
css-name 相当于css里的标签名:spin div p 啥的
-
如上我设置了这个按钮控件的类名为testButton
标签名为myButton -
它的Xml视图是这样的
xml<?xml version='1.0' encoding='UTF-8'?> <!-- Created with Cambalache 0.16.0 --> <interface> <!-- interface-name temp3.ui --> <requires lib="gtk" version="4.12"/> <object class="GtkButton" id="Button1"> <property name="css-classes">testButton</property> <property name="css-name">myButton</property> <property name="focusable">True</property> <property name="hexpand">True</property> <property name="label">Button1</property> <property name="vexpand">True</property> <property name="vexpand-set">True</property> </object> </interface>
css文件示例
css
.testButton{/*类选择器*/
background-color: blue; /* Green */
color: greenyellow;
border: none;
}
myButton {/*标签选择器*/
background-color: blue; /* Green */
color: greenyellow;
border: none;
}
/* 设置按钮在鼠标悬停时的背景色 */
myButton:hover {
background-color: red;
}
源代码
cpp
#include <gtkmm.h>
#include <iostream>
class MainWindow : public Gtk::Window
{
public:
// Member widgets:
MainWindow()
{
// Set window properties
set_title("GTKMM4 with CSS Example");
set_default_size(200, 200);
auto refBuilder= Gtk::Builder::create_from_file("K:\\VM_Shared\\temp3.ui");
auto pButton = refBuilder->get_widget<Gtk::Button>("Button1");
set_child(*pButton);
pButton->set_visible();
// Load CSS styles
load_css();
}
private:
void load_css()
{
// Check if CSS file exists
if (Glib::file_test("K:\\VM_Shared\\Style.css", Glib::FileTest::EXISTS))
{
// Create CSS provider and load CSS file
auto css_provider = Gtk::CssProvider::create();
css_provider->load_from_path("K:\\VM_Shared\\Style.css");
// Get the default screen and add the CSS provider
auto screen = Gdk::Display::get_default();
Gtk::StyleContext::add_provider_for_display(screen, css_provider,GTK_STYLE_PROVIDER_PRIORITY_APPLICATION );
}
else
{
std::cerr << "Failed to load CSS file: styles.css" << std::endl;
}
}
};
int main(int argc, char* argv[])
{
auto app=Gtk::Application::create("org.HelleCssExample");
return app->make_window_and_run<MainWindow>(argc, argv);
}