使用c++ cmake 调用gtk3接口实现一个简单的窗口
点按按钮会改变按钮文本为clicked
效果展示
编译运行方式
环境配置:
apt update && apt install libgtk-3-dev g++ cmake
编译方式:
cmake && make
运行:
./gtk-test
源码
main.cpp
#include <gtk/gtk.h>
#include <iostream>
//用于两个按钮的回调函数
void callback_btn(GtkApplication *app, gpointer user_data)
{
GtkButton *btn_a = (GtkButton *)user_data;
gtk_button_set_label(btn_a, "clicked"); //重命名按钮的文本
}
//gtk首次初始化会发出信号“activate”, 该函数作为此信号的回调函数
void activate(GtkApplication *app, gpointer user_data)
{
GtkWidget *win, *boxv, *boxh, *alert, *btn_a, *btn_b, *label_blank;
//设置窗口属性
win = gtk_application_window_new(app);
gtk_window_set_title(GTK_WINDOW(win), "Window");
gtk_widget_set_name(win, "alert01");
gtk_window_set_default_size(GTK_WINDOW(win), 400, 200);
// gtk_window_set_decorated(GTK_WINDOW(win), FALSE); //无边框
gtk_window_set_position(GTK_WINDOW(win), GTK_WIN_POS_CENTER);
//先创建一个垂直布局的box, 添加进窗口
//box可放置多个控件, 控件会按添加顺序依次垂直排列
boxv = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
gtk_container_add(GTK_CONTAINER(win), boxv);
//创建label控件, 设置横向与纵向自动扩展, 添加到box中
alert = gtk_label_new("text");
gtk_widget_set_hexpand(alert, TRUE);
gtk_widget_set_vexpand(alert, TRUE);
gtk_container_add(GTK_CONTAINER(boxv), alert);
//创建一个横向布局的box, 也添加进boxv中, 位于label下面
boxh = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
//创建三个控件, 添加进boxh中. 第一个空label设置横向自动扩展, 后面是两个按钮
//由于空label自动扩展, 这样两个按钮就会被挤到右下角
label_blank = gtk_label_new("");
gtk_widget_set_hexpand(label_blank, TRUE);
btn_a = gtk_button_new_with_label("btn01");
g_signal_connect(btn_a, "clicked", G_CALLBACK(callback_btn), btn_a);
btn_b = gtk_button_new_with_label("btn02");
g_signal_connect(btn_b, "clicked", G_CALLBACK(callback_btn), btn_b);
gtk_container_add(GTK_CONTAINER(boxh), label_blank);
gtk_container_add(GTK_CONTAINER(boxh), btn_a);
gtk_container_add(GTK_CONTAINER(boxh), btn_b);
gtk_container_add(GTK_CONTAINER(boxv), boxh);
//将控件设置为显示状态
gtk_widget_show_all (win);
}
int main(int argc, char **argv)
{
GtkApplication *app;
int status;
app = gtk_application_new("org.gtk.example", G_APPLICATION_DEFAULT_FLAGS);
g_signal_connect(app, "activate", G_CALLBACK(activate), NULL); //设置activate信号以及回调函数
status = g_application_run(G_APPLICATION(app), argc, argv);
g_object_unref(app);
return status;
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.0.0)
project(gtk_test VERSION 0.5.0 LANGUAGES C CXX)
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK3 REQUIRED gtk+-3.0)
include_directories(${GTK3_INCLUDE_DIRS})
link_directories(${GTK3_LIBRARY_DIRS})
list(APPEND FC_DEP_LIBS ${GTK3_LIBRARIES})
add_executable (gtk-test main.cpp)
target_link_libraries (gtk-test ${FC_DEP_LIBS})