Imgui常用控件的使用

我们首先清空上节课的所有的控件,然后创建一个最简单,没有任何控件的空白窗口。

#pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup")
#pragma execution_character_set("utf-8")

#include <GLFW/glfw3.h>
#include "imgui.h"
#include "backends/imgui_impl_glfw.h"
#include "backends/imgui_impl_opengl3.h"
#include <cstdio>
#include <string>
#include <fstream>
#include <windows.h>
#include <io.h>
#include <commdlg.h>  // 需要这个头文件

#include <iostream>
using namespace std;

// 设置字体,如果读者输入文本的时候是??的乱码
// 则需要在这里增加你所在环境的语言字体路径,或者使用系统默认字体路径
void SetupFont(ImGuiIO& io)
{
    // 常见中文字体路径(Windows)
    const char* font_path = "C:/Windows/Fonts/msyh.ttc"; // 微软雅黑
    float font_size = 18.0f;

    // 加载简体中文常用字范围
    ImVector<ImWchar> ranges;
    ImFontGlyphRangesBuilder builder;
    builder.AddRanges(io.Fonts->GetGlyphRangesChineseSimplifiedCommon());
    builder.BuildRanges(&ranges);

    // 添加字体
    io.Fonts->AddFontFromFileTTF(font_path, font_size, nullptr, ranges.Data);

    // 如果需要多语言支持,可以额外添加:
    // io.Fonts->AddFontFromFileTTF(font_path, font_size, nullptr, io.Fonts->GetGlyphRangesJapanese());
    // io.Fonts->AddFontFromFileTTF(font_path, font_size, nullptr, io.Fonts->GetGlyphRangesKorean());
}


int main()
{

    if (!glfwInit())
    {
        printf("GLFW init failed\n");
        return -1;
    }

    const char* glsl_version = "#version 330";
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    GLFWwindow* window = glfwCreateWindow(800, 600, "Title", nullptr, nullptr);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    glfwSwapInterval(1);

    IMGUI_CHECKVERSION();
    ImGui::CreateContext();
    ImGuiIO& io = ImGui::GetIO();
    ImGui::StyleColorsLight();

    SetupFont(io); // 设置字体,解决乱码问题

    ImGui_ImplGlfw_InitForOpenGL(window, true);
    ImGui_ImplOpenGL3_Init(glsl_version);

    while (!glfwWindowShouldClose(window))
    {
        glfwPollEvents();

        ImGui_ImplOpenGL3_NewFrame();
        ImGui_ImplGlfw_NewFrame();
        ImGui::NewFrame();

        ImGui::SetNextWindowPos(ImVec2(0, 0));
        ImGui::SetNextWindowSize(io.DisplaySize);

        ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoDecoration
            | ImGuiWindowFlags_NoMove
            | ImGuiWindowFlags_NoResize
            | ImGuiWindowFlags_NoSavedSettings;

        ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
        ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);

        ImGui::Begin("Title", nullptr, window_flags);

        //界面控件设置区域开始

        //结束

        ImGui::End();
        ImGui::PopStyleVar(2);

        ImGui::Render();
        int width, height;
        glfwGetFramebufferSize(window, &width, &height);
        glViewport(0, 0, width, height);
        glClearColor(0.12f, 0.12f, 0.12f, 1.f);
        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;
}Code language: C++ (cpp)

下面我们开始创建一个个的Imgui的控件。

文本框

ImGui::Text("Hello, world %d", 123);Code language: PHP (php)

就是从左上角开始,从左往右输出文本。

按钮

        //显示一个按钮,点击执行里面的代码
        if (ImGui::Button("Save"))
        {
            //点击后执行这里的代码
        }Code language: PHP (php)

控件太多了,我们直接看下面的例子,把所有的控件都输出出来

#pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup")
#pragma execution_character_set("utf-8")

#include <GLFW/glfw3.h>
#include "imgui.h"
#include "backends/imgui_impl_glfw.h"
#include "backends/imgui_impl_opengl3.h"
#include <cstdio>
#include <string>
#include <cstring>
#include <windows.h>
#include <io.h>
#include <iostream>
using namespace std;

// 设置字体,如果读者输入文本的时候是??的乱码
// 则需要在这里增加你所在环境的语言字体路径,或者使用系统默认字体路径
void SetupFont(ImGuiIO& io)
{
    // 常见中文字体路径(Windows)
    const char* font_path = "C:/Windows/Fonts/msyh.ttc"; // 微软雅黑
    float font_size = 18.0f;

    // 加载简体中文常用字范围
    ImVector<ImWchar> ranges;
    ImFontGlyphRangesBuilder builder;
    builder.AddRanges(io.Fonts->GetGlyphRangesChineseSimplifiedCommon());
    builder.BuildRanges(&ranges);

    // 添加字体
    io.Fonts->AddFontFromFileTTF(font_path, font_size, nullptr, ranges.Data);

    // 如果需要多语言支持,可以额外添加:
    // io.Fonts->AddFontFromFileTTF(font_path, font_size, nullptr, io.Fonts->GetGlyphRangesJapanese());
    // io.Fonts->AddFontFromFileTTF(font_path, font_size, nullptr, io.Fonts->GetGlyphRangesKorean());
}

// ===================== 全局控件绑定变量 =====================
char buf[256] = "单行输入框测试文字";
char bufMulti[1024] = "多行文本框\n第二行\n第三行中文测试";
float fVal = 0.5f;
int iVal = 50;
bool checkBox1 = false;
bool checkBox2 = true;
int radioIdx = 0;
int comboSel = 0;
ImVec4 color = ImVec4(0.2f, 0.7f, 0.9f, 1.0f);
bool showPopupWin = false;
bool showModal = false;
int tabIndex = 0;
float progress = 0.35f;

int main()
{
    SetConsoleOutputCP(65001);
    if (!glfwInit())
    {
        printf("GLFW init failed\n");
        return -1;
    }

    const char* glsl_version = "#version 330";
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    GLFWwindow* window = glfwCreateWindow(1000, 700, "ImGui 全部常用控件示例", nullptr, nullptr);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    glfwSwapInterval(1);

    IMGUI_CHECKVERSION();
    ImGui::CreateContext();
    ImGuiIO& io = ImGui::GetIO();
    ImGui::StyleColorsLight();

    SetupFont(io);

    ImGui_ImplGlfw_InitForOpenGL(window, true);
    ImGui_ImplOpenGL3_Init(glsl_version);

    while (!glfwWindowShouldClose(window))
    {
        glfwPollEvents();

        ImGui_ImplOpenGL3_NewFrame();
        ImGui_ImplGlfw_NewFrame();
        ImGui::NewFrame();

        ImGui::SetNextWindowPos(ImVec2(0, 0));
        ImGui::SetNextWindowSize(io.DisplaySize);

        ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoDecoration
            | ImGuiWindowFlags_NoMove
            | ImGuiWindowFlags_NoResize
            | ImGuiWindowFlags_NoSavedSettings;

        ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
        ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);

        ImGui::Begin("主窗口", nullptr, window_flags);

        // ========== 1. 顶部菜单栏 ==========
        if (ImGui::BeginMenuBar())
        {
            if (ImGui::BeginMenu("文件"))
            {
                if (ImGui::MenuItem("新建", "Ctrl+N")) {}
                if (ImGui::MenuItem("保存", "Ctrl+S")) {}
                ImGui::Separator();
                if (ImGui::MenuItem("退出"))
                    glfwSetWindowShouldClose(window, true);
                ImGui::EndMenu();
            }
            if (ImGui::BeginMenu("工具"))
            {
                if (ImGui::MenuItem("打开弹窗示例"))
                    showPopupWin = true;
                ImGui::EndMenu();
            }
            ImGui::EndMenuBar();
        }
        ImGui::Spacing();

        // ========== 2. 基础文本控件 ==========
        ImGui::Text("===== 文本类控件 =====");
        ImGui::Text("普通文本 Hello world %d", 123);
        ImGui::TextColored(ImVec4(1, 0, 0, 1), "红色彩色文本");
        ImGui::TextDisabled("灰色禁用文本");
        ImGui::BulletText("项目符号文字1");
        ImGui::BulletText("项目符号文字2");
        ImGui::Spacing();

        // ========== 3. 按钮系列 ==========
        ImGui::Text("===== 按钮控件 =====");
        if (ImGui::Button("普通按钮"))
            cout << "点击普通按钮" << endl;
        ImGui::SameLine();
        if (ImGui::SmallButton("小按钮"))
            cout << "点击小按钮" << endl;
        ImGui::SameLine();
        if (ImGui::Button("宽按钮", ImVec2(120, 0)))
            cout << "点击自定义宽按钮" << endl;
        ImGui::Spacing();

        // ========== 4. 输入框 ==========
        ImGui::Text("===== 输入框控件 =====");
        ImGui::InputText("单行文本输入", buf, IM_ARRAYSIZE(buf));
        ImGui::InputTextWithHint("带提示输入框", "请输入内容...", buf, IM_ARRAYSIZE(buf));
        ImGui::InputFloat("浮点数输入", &fVal);
        ImGui::InputInt("整数输入", &iVal);
        ImGui::Spacing();
        ImGui::Text("多行文本框:");
        ImVec2 multiSize = ImVec2(500, 80);
        ImGui::InputTextMultiline("##multi", bufMulti, IM_ARRAYSIZE(bufMulti), multiSize);
        ImGui::Spacing();

        // ========== 5. 滑块、拖动条 ==========
        ImGui::Text("===== 滑块/拖动条 =====");
        ImGui::SliderFloat("浮点滑块", &fVal, 0.0f, 1.0f);
        ImGui::SliderInt("整数滑块", &iVal, 0, 100);
        ImGui::DragFloat("拖动条float", &fVal, 0.01f);
        ImGui::DragInt("拖动条int", &iVal, 1.0f);
        ImGui::Spacing();

        // ========== 6. 复选框、单选框 ==========
        ImGui::Text("===== 复选框 & 单选框 =====");
        ImGui::Checkbox("复选框A", &checkBox1);
        ImGui::Checkbox("复选框B", &checkBox2);
        ImGui::Text("单选组:");
        ImGui::RadioButton("选项1", &radioIdx, 0); ImGui::SameLine();
        ImGui::RadioButton("选项2", &radioIdx, 1); ImGui::SameLine();
        ImGui::RadioButton("选项3", &radioIdx, 2);
        ImGui::Spacing();

        // ========== 7. 下拉选择框 ==========
        ImGui::Text("===== 下拉框 Combo =====");
        const char* items[] = { "选项A", "选项B", "选项C", "选项D" };
        ImGui::Combo("下拉选择", &comboSel, items, IM_ARRAYSIZE(items));
        ImGui::Spacing();

        // ========== 8. 颜色选择器 ==========
        ImGui::Text("===== 颜色拾取器 =====");
        ImGui::ColorEdit4("RGBA颜色", (float*)&color);
        ImGui::ColorButton("色块预览", color);
        ImGui::Spacing();

        // ========== 9. 进度条、分隔线 ==========
        ImGui::Text("===== 进度条/分隔线 =====");
        ImGui::ProgressBar(progress, ImVec2(300, 0));
        ImGui::Text("进度数值:%.2f", progress);
        ImGui::Separator(); // 水平分隔线
        ImGui::Spacing();

        // ========== 10. 折叠树节点 ==========
        ImGui::Text("===== 折叠树形节点 =====");
        if (ImGui::CollapsingHeader("折叠面板 点击展开"))
        {
            ImGui::Text("面板内部内容");
            ImGui::Button("面板内按钮");
        }
        if (ImGui::TreeNode("树形节点"))
        {
            ImGui::BulletText("子项1");
            ImGui::BulletText("子项2");
            ImGui::TreePop();
        }
        ImGui::Spacing();

        // ========== 11. 标签页 TabBar ==========
        ImGui::Text("===== 标签页 Tab =====");
        ImGui::BeginTabBar("TabBar");
        if (ImGui::BeginTabItem("标签1"))
        {
            ImGui::Text("标签1页面内容");
            ImGui::EndTabItem();
        }
        if (ImGui::BeginTabItem("标签2"))
        {
            ImGui::Text("标签2页面内容");
            ImGui::EndTabItem();
        }
        ImGui::EndTabBar();
        ImGui::Spacing();

        // ========== 12. 表格 Table ==========
        ImGui::Text("===== 表格控件 =====");
        if (ImGui::BeginTable("table1", 3, ImGuiTableFlags_Borders))
        {
            ImGui::TableSetupColumn("序号");
            ImGui::TableSetupColumn("名称");
            ImGui::TableSetupColumn("数值");
            ImGui::TableHeadersRow();

            // 行1
            ImGui::TableNextRow();
            ImGui::TableNextColumn(); ImGui::Text("1");
            ImGui::TableNextColumn(); ImGui::Text("测试A");
            ImGui::TableNextColumn(); ImGui::Text("%.2f", fVal);
            // 行2
            ImGui::TableNextRow();
            ImGui::TableNextColumn(); ImGui::Text("2");
            ImGui::TableNextColumn(); ImGui::Text("测试B");
            ImGui::TableNextColumn(); ImGui::Text("%d", iVal);
            ImGui::EndTable();
        }
        ImGui::Spacing();

        // ========== 13. 右键弹出菜单 ==========
        ImGui::Text("===== 右键菜单(在此文字上右键) =====");
        if (ImGui::IsItemClicked(ImGuiMouseButton_Right))
            ImGui::OpenPopup("RightMenu");
        if (ImGui::BeginPopup("RightMenu"))
        {
            ImGui::MenuItem("右键菜单项1");
            ImGui::MenuItem("右键菜单项2");
            ImGui::Separator();
            ImGui::MenuItem("关闭菜单");
            ImGui::EndPopup();
        }
        ImGui::Spacing();

        // ========== 14. 普通弹窗(非模态) ==========
        if (showPopupWin)
        {
            ImGui::OpenPopup("PopupWindow");
            showPopupWin = false;
        }
        if (ImGui::BeginPopup("PopupWindow"))
        {
            ImGui::Text("普通弹窗,可操作主窗口");
            if (ImGui::Button("关闭弹窗"))
                ImGui::CloseCurrentPopup();
            ImGui::EndPopup();
        }

        // ========== 15. 模态弹窗 Modal ==========
        if (ImGui::Button("打开模态弹窗"))
            showModal = true;
        if (showModal)
        {
            ImGui::OpenPopup("ModalDialog");
            showModal = false;
        }
        if (ImGui::BeginPopupModal("模态对话框", nullptr, ImGuiWindowFlags_AlwaysAutoResize))
        {
            ImGui::Text("模态弹窗会锁定主窗口,必须点确认关闭");
            if (ImGui::Button("确认", ImVec2(120, 0)))
            {
                ImGui::CloseCurrentPopup();
            }
            ImGui::EndPopup();
        }

        ImGui::End();
        ImGui::PopStyleVar(2);

        ImGui::Render();
        int width, height;
        glfwGetFramebufferSize(window, &width, &height);
        glViewport(0, 0, width, height);
        glClearColor(0.12f, 0.12f, 0.12f, 1.f);
        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;
}Code language: C++ (cpp)

读者可以慢慢体会这些控件的用法。

控件很丰富,基本的简单工具软件开发,完全满足。例如折叠树,TAB选项卡各种表单控件,单行 多行文本 单选 复选框 下拉框 都又

进度条,折叠面板 表格,右键菜单,颜色选择,等等。读者可以自己尝试一下。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注