参照rust-gtk4文档,用rust学习使用GTK4开发,按照官网文档代码写一遍发现代码总编译失败,一会儿缺pkg-config,一会儿提示少glib-sys。于是整理下GTK4安装过程。
操作系统
Windows 10
一、安装MSYS2
MSYS2 官网: www.msys2.org
点击网页中的 exe文件下载即可,安装过程非常简单,选择一个路径安装完成。
二、安装gtk4
输入以下命令安装gtk4, pkgconf, gcc, glib等工具,少了可能会导致cargo build 报错,编译失败。
pacman -S mingw-w64-x86_64-gtk4 mingw-w64-x86_64-gettext mingw-w64-x86_64-libxml2 mingw-w64-x86_64-librsvg mingw-w64-x86_64-pkgconf mingw-w64-x86_64-gcc glib2
三、配置环境变量
选择用户变量中的Path
,将msys64下的bin
, lib
, include
3个目录都加入环境变量。
(注意,记得将msys64的路径修改为自己安装的位置)
D:\Tools\msys64\mingw64\bin
D:\Tools\msys64\mingw64\lib
D:\Tools\msys64\mingw64\include
三、为Rust设置 GNU toolchain
rustup toolchain install stable-gnu
rustup default stable-gnu
四、测试
用官方文档里的Hello world跑起来试试。
文档链接: https://gtk-rs.org/gtk4-rs/stable/latest/book/hello_world.html
Cargo.toml
[dependencies]
gtk = { version = "0.6.6", package = "gtk4", features = ["v4_10"] }
main.rs
use gtk::prelude::*;
use gtk::{glib, Application, ApplicationWindow, Button};
const APP_ID: &str = "org.gtk_rs.HelloWorld3";
fn main() -> glib::ExitCode {
// Create a new application
let app = Application::builder().application_id(APP_ID).build();
// Connect to "activate" signal of `app`
app.connect_activate(build_ui);
// Run the application
app.run()
}
fn build_ui(app: &Application) {
// Create a button with label and margins
let button = Button::builder()
.label("Press me!")
.margin_top(12)
.margin_bottom(12)
.margin_start(12)
.margin_end(12)
.build();
// Connect to "clicked" signal of `button`
button.connect_clicked(|button| {
// Set the label to "Hello World!" after the button has been clicked on
button.set_label("Hello World!");
});
// Create a window
let window = ApplicationWindow::builder()
.application(app)
.title("My GTK App")
.child(&button)
.build();
// Present window
window.present();
}