您可以使用此示例gtk::GestureClick
中所示的方法来执行此操作。
这是一个完整的示例(单击窗口内的某处,因为该框实际上不可见):
use gtk::prelude::*;
use gtk::{Application, ApplicationWindow};
fn main() {
// Create a new application
let app = Application::builder()
.application_id("org.gtk-rs.example")
.build();
// Connect to "activate" signal of `app`
app.connect_activate(|app| {
build_ui(app);
});
// Run the application
app.run();
}
fn build_ui(app: &Application) {
// Create a window and set the title
let window = ApplicationWindow::builder()
.application(app)
.title("My GTK App")
.build();
// Create a box
let gtk_box = gtk::builders::BoxBuilder::new()
.height_request(200)
.width_request(300)
.build();
// Assign a click listener
let gesture = gtk::GestureClick::new();
gesture.connect_released(|gesture, _, _, _| {
gesture.set_state(gtk::EventSequenceState::Claimed);
println!("Box pressed!");
});
gtk_box.add_controller(&gesture);
// Add the box
window.set_child(Some(>k_box));
// Present window to the user
window.present();
}
一个更复杂的例子
假设您实际上还想查看该框,并可能提供一些有关鼠标悬停的用户反馈。然后,您将需要使用 CSS 规则来实现这一点。
将您更改main.rs
为:
use gtk::gdk::Display;
use gtk::{CssProvider, StyleContext, prelude::*};
use gtk::{Application, ApplicationWindow};
fn main() {
// Create a new application
let app = Application::builder()
.application_id("org.gtk-rs.example")
.build();
// Connect to "activate" signal of `app`
app.connect_activate(|app| {
// Load a CSS stylesheet from the included bytes.
let provider = CssProvider::new();
provider.load_from_data(include_bytes!("style.css"));
// Give the CssProvider to the default screen so the CSS rules are
// applied to the window.
StyleContext::add_provider_for_display(
&Display::default().expect("Error initializing gtk css provider."),
&provider,
gtk::STYLE_PROVIDER_PRIORITY_APPLICATION,
);
build_ui(app);
});
// Run the application
app.run();
}
fn build_ui(app: &Application) {
// Create a window and set the title
let window = ApplicationWindow::builder()
.application(app)
.title("My GTK App")
.build();
// Create a box
let gtk_box = gtk::builders::BoxBuilder::new()
.height_request(200)
.width_request(300)
.margin_bottom(20)
.margin_end(20)
.margin_start(20)
.margin_top(20)
.css_classes(vec![String::from("hover-box")])
.build();
// Assign a click listener
let gesture = gtk::GestureClick::new();
gesture.connect_released(|gesture, _, _, _| {
gesture.set_state(gtk::EventSequenceState::Claimed);
println!("Box pressed!");
});
gtk_box.add_controller(&gesture);
// Add the box
window.set_child(Some(>k_box));
// Present window to the user
window.present();
}
并在目录(所在目录)中创建一个style.css
文件,内容如下:src/
main.rs
.hover-box {
background-color: blue;
border-radius: 5px;
}
.hover-box:hover {
background-color: rgb(11, 133, 240);
border-radius: 5px;
}
现在,当您将鼠标悬停在框上方时,您会得到gtk4::Box
一个5px
边框半径和背景颜色会发生变化的图形。blue