windows 下开发 gtk4

目标:构建一个跨平台的文件上传下载的应用。

注:可以从bilibili获取完整的视频教程 windows gtk4开发

环境安装过程

# 1. 下载msys2
# https://www.msys2.org/

# 2. 配置msys2的源
# https://mirrors.tuna.tsinghua.edu.cn/help/msys2/

# 3. 下载编译工具链与gcc
pacman -S pacman -S mingw-w64-x86_64-toolchain base-devel mingw-w64-x86_64-gcc

# 4. 安装gtk4
pacman -S mingw-w64-x86_64-gtk4

# 5. 安装 libadwata
pacman -S mingw-w64-x86_64-libadwaita

校验安装完整性

pkg-config --cflags --libs gtk4
pkg-config.exe --libs --cflags libadwaita-1

配置CMakeLists.txt

cmake_minimum_required(VERSION 3.23)
project(GtkUploader C)

set(CMAKE_C_STANDARD 23)

find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK4 REQUIRED gtk4)

include_directories(${GTK4_INCLUDE_DIRS})
link_directories(${GTK4_LIBRARY_DIRS})

add_executable(GtkUploader main.c)
target_link_libraries(GtkUploader ${GTK4_LIBRARIES})

配置cmake的libadwaita支持

cmake_minimum_required(VERSION 3.23)
project(GtkUploader C)

set(CMAKE_C_STANDARD 23)

find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK4 REQUIRED gtk4)
pkg_check_modules(ADWAITA libadwaita-1 REQUIRED)

include_directories(${GTK4_INCLUDE_DIRS})
link_directories(${GTK4_LIBRARY_DIRS})

add_executable(GtkUploader main.c)
target_link_libraries(GtkUploader ${GTK4_LIBRARIES} ${ADWAITA_LIBRARIES})

一个获取时间戳的demo

#include <gtk/gtk.h>
#include <libadwaita-1/adwaita.h>
#include <glib/gprintf.h>

static void activate_refresh_time(GtkButton * button, GtkEntryBuffer *raw_data) {
    gint64 time_now = g_get_real_time();
    printf("%d", time_now);
    char datetime [10];
    sprintf(datetime, "%d", time_now);
    gtk_entry_buffer_set_text(raw_data, datetime, 10);
}

static void
activate_cb (GtkApplication *app)
{
    GtkWidget *window = gtk_application_window_new (app);
    gtk_window_set_title (GTK_WINDOW (window), "Echo Datetime");
    gtk_window_set_default_size (GTK_WINDOW (window), 400, 400);

    GtkButton *refresh_time = gtk_button_new_with_label("refresh");
    GtkEntryBuffer *raw_data = gtk_entry_buffer_new(NULL, 0);
    g_signal_connect (refresh_time, "clicked", G_CALLBACK (activate_refresh_time), raw_data);
    GtkText *output = gtk_text_new_with_buffer(raw_data);

    GtkBox * box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10);

    gtk_box_append(box, output);
    gtk_box_append(box, refresh_time);

    gtk_widget_show(box);

    gtk_window_set_child (GTK_WINDOW (window), box);
    gtk_window_present (GTK_WINDOW (window));
}

int
main (int   argc,
      char *argv[])
{
    g_autoptr (AdwApplication) app = NULL;
    app = adw_application_new ("com.github.xuthus5", G_APPLICATION_FLAGS_NONE);
    g_signal_connect (app, "activate", G_CALLBACK (activate_cb), NULL);
    return g_application_run (G_APPLICATION (app), argc, argv);
}

构建项目的UI雏形

运行MSYS2安装glade,需要注意的是,glade已经停止维护了,而且只支持GTK3的语法。

# 安装glade
# 官网 https://glade.gnome.org/
pacman -S mingw-w64-x86_64-glade

将UI导入到项目中

gtk4-builder-tool simplify --3to4 --replace ./ui.glade

使用 GResources

todo...

更换cmake为meson

todo...

项目工程化

todo...