C++的跨平臺桌面GUI庫有很多,大體上分成兩種流派:retained mode和immediate mode。
- 其中前者是主流的桌面GUI機制框架,包括:Qt、wxwidgets、gtk、juce等
- 后者是一些游戲引擎編輯器常用的GUI機制框架,包括:imgui、nanogui等
使用這些框架都支持構(gòu)建在windows、mac、linux上面能運行的桌面圖形界面程序。
但如果在開發(fā)小工具項目,要求跨平臺、開源免費、協(xié)議友好、性能高、輕量級的需求,這里推薦FLTK庫(https://www.fltk.org/),只需要作為一個依賴庫的方式引入工程即可。
以下是一個使用FLTK開發(fā)的簡單demo代碼示例,功能是顯示一個編輯框和一個按鈕,點擊按鈕刷新編輯框的數(shù)字。
項目結(jié)構(gòu)
fltk_demo
- fltk-1.3.8
- src
|- main.cpp
- CMakeLists.txt
CMakeLists.txt
cmake_minimum_required(VERSION 3.0)
project(fltk_demo)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
if (WIN32)
set(CMAKE_EXE_LINKER_FLAGS "/SUBSYSTEM:WINDOWS /ENTRY:mainCRTStartup") # do not pop out console for release
endif()
if (WIN32)
add_definitions(
-D_CRT_SECURE_NO_WARNINGS
-D_WINSOCK_DEPRECATED_NO_WARNINGS
)
endif()
add_subdirectory(fltk-1.3.8)
include_directories(fltk-1.3.8)
file(GLOB SRC
src/*.h
src/*.cpp
)
add_executable(${PROJECT_NAME} ${SRC})
# both win and linux use the same lib name
target_link_libraries(${PROJECT_NAME}
fltk
)
main.cpp
#include <iostream>
#include <string>
#include "FL/Fl.H"
#include "FL/Fl_Window.H"
#include "FL/Fl_Box.H"
#include "FL/Fl_Input.H"
#include "FL/Fl_Button.H"
class MyWindow : public Fl_Window
{
public:
MyWindow(int w, int h, const char* title) : Fl_Window(w, h, title)
{}
void init()
{
std::cout << "MyWindow init" << std::endl;
// ui
begin();
color(FL_DARK3);
int y = 10;
s_input = new Fl_Input(150, y, 100, 20, "Number:");
s_input->static_value(s_num_str.c_str()); // set init text
y += 30;
Fl_Button* add_button = new Fl_Button(150, y, 60, 30, "Add Num");
resizable(add_button);
add_button->callback(handleAddButtonClick);
end();
}
static void handleAddButtonClick(Fl_Widget* widget, void* v)
{
std::cout << "MyWindow handleAddButtonClick" << std::endl;
// update text
int num = atoi(s_num_str.c_str());
num++;
s_num_str = std::to_string(num);
std::cout << "add num to " << num << std::endl;
s_input->static_value(s_num_str.c_str());
s_input->redraw();
}
private:
static Fl_Input* s_input;
static std::string s_num_str;
};
Fl_Input* MyWindow::s_input = nullptr;
std::string MyWindow::s_num_str = "0";
#include <string>
#include <algorithm>
int main(int argc, char** argv)
{
MyWindow* my_window = new MyWindow(400, 300, "MyWindow");
my_window->init();
my_window->show();
return Fl::run();
}
其中文章來源:http://www.zghlxwxcb.cn/news/detail-474885.html
- cmake配置里面需要增加編譯選項,可以避免界面啟動后彈出控制臺黑框,如果作為debug階段可以保留
- 控件綁定的回調(diào)函數(shù)必須是全局或者靜態(tài)函數(shù)
效果
源碼
https://download.csdn.net/download/u012234115/87878308文章來源地址http://www.zghlxwxcb.cn/news/detail-474885.html
到了這里,關(guān)于C++輕量級跨平臺桌面GUI庫FLTK的簡單使用的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!