Linux C++ 图形界面开发实战指南
一 开发流程与要点
二 常用 GUI 框架选型对比
| 框架 | 核心特点 | 典型场景 | 学习难度 |
|---|---|---|---|
| Qt | 跨平台、控件丰富、信号与槽、工具链完善(Qt Creator、rcc、uic) | 企业级桌面、复杂交互、需要多平台一致体验 | 中 |
| wxWidgets | 跨平台、倾向原生外观、C++ 接口 | 需要“更像原生”的桌面应用 | 中 |
| GTK / gtkmm | Linux/GNOME 生态、C 编写(C++ 用 gtkmm)、GObject 信号 | 遵循 GNOME 规范的应用 | 中-高 |
| FLTK | 轻量、跨平台、依赖少、自带简单 UI 设计器 | 小型工具、教学/原型 | 低 |
| Dear ImGui | 即时模式、代码即界面、依赖极小、与 OpenGL/Vulkan 等后端配合 | 调试面板、工具、嵌入式可视化 | 低-中 |
上述框架的定位、特性与生态在多篇技术资料与百科条目中有系统介绍,可作为选型参考。
三 快速上手示例
Qt 最小示例(CMake 推荐)
// main.cpp
#include <QApplication>
#include <QPushButton>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QPushButton btn("Hello, Qt");
btn.resize(200, 60);
btn.show();
return app.exec();
}
cmake_minimum_required(VERSION 3.16)
project(HelloQt CXX)
set(CMAKE_CXX_STANDARD 17)
find_package(Qt6 REQUIRED COMPONENTS Widgets)
add_executable(hello_qt main.cpp)
target_link_libraries(hello_qt Qt6::Widgets)
mkdir build && cd build
cmake -G Ninja ..
ninja
./hello_qt
GTKmm 最小示例(C++ 绑定)
// main.cpp
#include <gtkmm.h>
int main(int argc, char *argv[]) {
auto app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
Gtk::Window window;
window.set_title("Hello, GTKmm");
window.set_default_size(200, 100);
Gtk::Button btn("Click me");
btn.signal_clicked().connect([](){ g_print("Hello, GTKmm!\n"); });
window.add(btn);
window.show_all();
return app->run(window);
}
sudo apt-get update
sudo apt-get install libgtkmm-3.0-dev
g++ main.cpp -o gtkmm_app `pkg-config --cflags --libs gtkmm-3.0`
./gtkmm_app
Dear ImGui 最小示例(GLFW + OpenGL3 后端)
// main.cpp
#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
#include <GLFW/glfw3.h>
#include <stdio.h>
int main() {
if (!glfwInit()) return 1;
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
GLFWwindow* window = glfwCreateWindow(800, 600, "Hello, ImGui", nullptr, nullptr);
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGui_ImplGlfw_InitForOpenGL(window, true);
ImGui_ImplOpenGL3_Init("#version 130");
while (!glfwWindowShouldClose(window)) {
glfwPollEvents();
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
ImGui::Begin("Hello, Linux");
static int cnt = 0;
if (ImGui::Button("Click me")) ++cnt;
ImGui::Text("Count = %d", cnt);
ImGui::End();
ImGui::Render();
int w, h;
glfwGetFramebufferSize(window, &w, &h);
glViewport(0, 0, w, h);
glClear(GL_COLOR_BUFFER_BIT);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
glfwSwapBuffers(window);
}
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
# 克隆 imgui 仓库后进入示例目录
cd imgui/examples/example_glfw_opengl3
make
./example_glfw_opengl3
四 工程化与最佳实践
AUTOMOC/AUTORCC 简化元对象与资源处理。五 常见坑与排查