-
本篇笔记基于油管大神的博客学习https://prognotes.net/2016/03/gtk-3-c-code-hello-world-tutorial-using-glade-3/ 连接
-
使用
glade
拖拽一个界面出来- 界面包含一个
window
,一个fixed
,两个label
和一个button
保存为glades/03class/myglade.glade
- 界面包含一个
-
编写
main.cpp
#include <gtk/gtk.h> #include <string.h> #include <string> using namespace std; void on_window_main_destroy() { gtk_main_quit(); } GtkWidget *labelHelloText; GtkWidget *labelHelloCount; void on_button_count_clicked() { static int count = 0; string text = "helloword"; count ++; gtk_label_set_text(GTK_LABEL(labelHelloCount), to_string(count).c_str()); gtk_label_set_text(GTK_LABEL(labelHelloText), text.c_str()); } int main(int argc, char **argv) { GtkBuilder *builder; GtkWidget *window; gtk_init(&argc, &argv); builder = gtk_builder_new(); char* filePath = "glades/03class/myglade.glade"; gtk_builder_add_from_file(builder, filePath, NULL); gtk_builder_connect_signals(builder, NULL); window = GTK_WIDGET(gtk_builder_get_object(builder, "window_main")); g_signal_connect(window, "delete_event", on_window_main_destroy, NULL); labelHelloText = GTK_WIDGET(gtk_builder_get_object(builder, "lbl_hello")); labelHelloCount = GTK_WIDGET(gtk_builder_get_object(builder, "lbl_count")); GtkWidget *btn = GTK_WIDGET(gtk_builder_get_object(builder, "btn_hello")); { // 这里连接信号是因为,c++里有命名粉碎机制,所以从ui文件拿不到绑定的信号回调函数 // 在 C 里应该没问题的 g_signal_connect(btn, "clicked", on_button_count_clicked, NULL); g_signal_connect(window, "delete_event", gtk_main_quit, NULL); } g_object_unref(builder); gtk_widget_show_all(window); gtk_main(); return 0; }
-
编译运行就行了