在Linux環境下,利用Rust進行圖形界面(GUI)開發有多種選擇。以下是一些流行的庫和框架:
GTK+ 是一個跨平臺的圖形用戶界面工具包,廣泛用于Linux、Windows和macOS。Rust有一個名為 gtk-rs 的綁定庫,可以用來在Rust中使用GTK+。
首先,確保你已經安裝了GTK+開發庫:
sudo apt-get install libgtk-3-dev
然后,添加 gtk 依賴到你的 Cargo.toml 文件中:
[dependencies]
gtk = "0.9" # 請檢查最新版本
use gtk::prelude::*;
use gtk::{Button, Window, WindowType};
fn main() {
// 初始化GTK
if gtk::init().is_err() {
println!("Failed to initialize GTK.");
return;
}
// 創建一個窗口
let window = Window::new(WindowType::Toplevel);
// 設置窗口標題
window.set_title("Hello, Rust GTK!");
// 創建一個按鈕
let button = Button::with_label("Click me!");
// 設置按鈕點擊事件
button.connect_clicked(|_| {
println!("Button clicked!");
});
// 將按鈕添加到窗口
window.add(&button);
// 顯示所有組件
window.show_all();
// 連接關閉事件
window.connect_delete_event(|_, _| {
gtk::main_quit();
Inhibit(false)
});
// 運行GTK主循環
gtk::main();
}
Qt 是另一個流行的跨平臺圖形用戶界面工具包。Rust有一個名為 qmetaobject-rs 的綁定庫,可以用來在Rust中使用Qt。
首先,確保你已經安裝了Qt開發庫:
sudo apt-get install qt5-default
然后,添加 qmetaobject 依賴到你的 Cargo.toml 文件中:
[dependencies]
qmetaobject = "0.10" # 請檢查最新版本
use qmetaobject::{
qt_class, qt_method, qt_signal, Qt,
};
use std::os::raw::{c_char};
#[qt_class]
struct MyWindow {
base: super::QObject,
}
#[qt_method]
impl MyWindow {
fn new() -> Self {
Self {
base: super::QObject::new(),
}
}
fn show(&self) {
println!("Window shown!");
}
}
#[qt_signal]
impl MyWindow {
fn closed() {
println!("Window closed!");
}
}
fn main() {
// 初始化Qt
qmetaobject::qt_initialize().expect("Failed to initialize Qt");
// 創建一個窗口
let window = MyWindow::new();
// 顯示窗口
window.show();
// 運行Qt主循環
qmetaobject::qt_exec();
}
Iced 是一個用Rust編寫的聲明式GUI庫,靈感來自Elm。它非常適合構建現代、響應式的用戶界面。
首先,添加 iced 依賴到你的 Cargo.toml 文件中:
[dependencies]
iced = "0.4" # 請檢查最新版本
use iced::{
executor, Align, Application, Button, Column, Command, Element, Length, Settings, Text,
};
struct MyApp {
counter: i32,
}
#[derive(Debug, Clone, Copy)]
enum Message {
Increment,
Decrement,
}
impl Application for MyApp {
type Executor = executor::Default;
type Message = Message;
type Flags = ();
fn new(_flags: ()) -> (Self, Command<Message>) {
(MyApp { counter: 0 }, Command::none())
}
fn title(&self) -> String {
String::from("Iced Example")
}
fn update(&mut self, message: Message) -> Command<Message> {
match message {
Message::Increment => self.counter += 1,
Message::Decrement => self.counter -= 1,
}
Command::none()
}
fn view(&mut self) -> Element<Message> {
Column::new()
.align_items(Align::Center)
.spacing(20)
.push(Text::new(format!("Counter: {}", self.counter)))
.push(Button::new(&mut self.counter, Message::Increment).text("Increment"))
.push(Button::new(&mut self.counter, Message::Decrement).text("Decrement"))
}
}
fn main() {
MyApp::run(Settings::default()).unwrap();
}
這些庫和框架各有特點,你可以根據自己的需求選擇合適的工具進行圖形界面開發。