Usage of Common ImGui Widgets

First, we will clear all widgets from the previous lesson and create a minimal blank window with zero controls inside.

#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>  // Required header for file dialogs

#include <iostream>
using namespace std;

// Configure font to fix garbled "??" characters
// Add font path matching your OS environment here, or use system default font path
void SetupFont(ImGuiIO& io)
{
    // Common Chinese font path for Windows
    const char* font_path = "C:/Windows/Fonts/msyh.ttc"; // Microsoft YaHei
    float font_size = 18.0f;

    // Load commonly used Simplified Chinese character range
    ImVector<ImWchar> ranges;
    ImFontGlyphRangesBuilder builder;
    builder.AddRanges(io.Fonts->GetGlyphRangesChineseSimplifiedCommon());
    builder.BuildRanges(&ranges);

    // Load custom font
    io.Fonts->AddFontFromFileTTF(font_path, font_size, nullptr, ranges.Data);

    // Add extra font ranges for multi-language support if needed:
    // 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); // Load font to resolve garbled text issue

    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);

        // Widget rendering area start

        // End of widget area

        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)

Now we will create ImGui widgets one by one.

Text Widget

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

It renders text left-to-right starting from the top-left corner.

Button

        // Render a button; inner code executes on click
        if (ImGui::Button("Save"))
        {
            // Code here runs after clicking
        }Code language: PHP (php)

There are dozens of widgets available. Let’s look at the complete demo code below that renders all common widgets at once.

#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;

// Configure font to fix garbled "??" characters
// Add font path matching your OS environment here, or use system default font path
void SetupFont(ImGuiIO& io)
{
    // Common Chinese font path for Windows
    const char* font_path = "C:/Windows/Fonts/msyh.ttc"; // Microsoft YaHei
    float font_size = 18.0f;

    // Load commonly used Simplified Chinese character range
    ImVector<ImWchar> ranges;
    ImFontGlyphRangesBuilder builder;
    builder.AddRanges(io.Fonts->GetGlyphRangesChineseSimplifiedCommon());
    builder.BuildRanges(&ranges);

    // Load custom font
    io.Fonts->AddFontFromFileTTF(font_path, font_size, nullptr, ranges.Data);

    // Add extra font ranges for multi-language support if needed:
    // io.Fonts->AddFontFromFileTTF(font_path, font_size, nullptr, io.Fonts->GetGlyphRangesJapanese());
    // io.Fonts->AddFontFromFileTTF(font_path, font_size, nullptr, io.Fonts->GetGlyphRangesKorean());
}

// ===================== Global variables bound to widgets =====================
char buf[256] = "Single-line input test text";
char bufMulti[1024] = "Multi-line text box\nLine 2\nLine 3 Chinese test";
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 All Common Widget Demo", 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("Main Window", nullptr, window_flags);

        // ========== 1. Top Menu Bar ==========
        if (ImGui::BeginMenuBar())
        {
            if (ImGui::BeginMenu("File"))
            {
                if (ImGui::MenuItem("New", "Ctrl+N")) {}
                if (ImGui::MenuItem("Save", "Ctrl+S")) {}
                ImGui::Separator();
                if (ImGui::MenuItem("Exit"))
                    glfwSetWindowShouldClose(window, true);
                ImGui::EndMenu();
            }
            if (ImGui::BeginMenu("Tools"))
            {
                if (ImGui::MenuItem("Open Popup Demo"))
                    showPopupWin = true;
                ImGui::EndMenu();
            }
            ImGui::EndMenuBar();
        }
        ImGui::Spacing();

        // ========== 2. Basic Text Widgets ==========
        ImGui::Text("===== Text Widgets =====");
        ImGui::Text("Normal Text Hello world %d", 123);
        ImGui::TextColored(ImVec4(1, 0, 0, 1), "Red Colored Text");
        ImGui::TextDisabled("Gray Disabled Text");
        ImGui::BulletText("Bullet point text 1");
        ImGui::BulletText("Bullet point text 2");
        ImGui::Spacing();

        // ========== 3. Button Family ==========
        ImGui::Text("===== Buttons =====");
        if (ImGui::Button("Normal Button"))
            cout << "Normal button clicked" << endl;
        ImGui::SameLine();
        if (ImGui::SmallButton("Small Button"))
            cout << "Small button clicked" << endl;
        ImGui::SameLine();
        if (ImGui::Button("Wide Button", ImVec2(120, 0)))
            cout << "Custom wide button clicked" << endl;
        ImGui::Spacing();

        // ========== 4. Input Fields ==========
        ImGui::Text("===== Input Widgets =====");
        ImGui::InputText("Single Line Input", buf, IM_ARRAYSIZE(buf));
        ImGui::InputTextWithHint("Hinted Input", "Type content here...", buf, IM_ARRAYSIZE(buf));
        ImGui::InputFloat("Float Input", &fVal);
        ImGui::InputInt("Integer Input", &iVal);
        ImGui::Spacing();
        ImGui::Text("Multi-line Text Box:");
        ImVec2 multiSize = ImVec2(500, 80);
        ImGui::InputTextMultiline("##multi", bufMulti, IM_ARRAYSIZE(bufMulti), multiSize);
        ImGui::Spacing();

        // ========== 5. Sliders & Drag Bars ==========
        ImGui::Text("===== Sliders / Drag Controls =====");
        ImGui::SliderFloat("Float Slider", &fVal, 0.0f, 1.0f);
        ImGui::SliderInt("Integer Slider", &iVal, 0, 100);
        ImGui::DragFloat("Drag Float", &fVal, 0.01f);
        ImGui::DragInt("Drag Int", &iVal, 1.0f);
        ImGui::Spacing();

        // ========== 6. Checkboxes & Radio Buttons ==========
        ImGui::Text("===== Checkboxes & Radio Buttons =====");
        ImGui::Checkbox("Checkbox A", &checkBox1);
        ImGui::Checkbox("Checkbox B", &checkBox2);
        ImGui::Text("Radio Group:");
        ImGui::RadioButton("Option 1", &radioIdx, 0); ImGui::SameLine();
        ImGui::RadioButton("Option 2", &radioIdx, 1); ImGui::SameLine();
        ImGui::RadioButton("Option 3", &radioIdx, 2);
        ImGui::Spacing();

        // ========== 7. Combo Dropdown ==========
        ImGui::Text("===== Combo Dropdown =====");
        const char* items[] = { "Option A", "Option B", "Option C", "Option D" };
        ImGui::Combo("Dropdown Select", &comboSel, items, IM_ARRAYSIZE(items));
        ImGui::Spacing();

        // ========== 8. Color Picker ==========
        ImGui::Text("===== Color Editor =====");
        ImGui::ColorEdit4("RGBA Color", (float*)&color);
        ImGui::ColorButton("Color Preview Swatch", color);
        ImGui::Spacing();

        // ========== 9. Progress Bar & Separators ==========
        ImGui::Text("===== Progress Bar / Separators =====");
        ImGui::ProgressBar(progress, ImVec2(300, 0));
        ImGui::Text("Progress Value: %.2f", progress);
        ImGui::Separator(); // Horizontal dividing line
        ImGui::Spacing();

        // ========== 10. Collapsible Tree Nodes ==========
        ImGui::Text("===== Collapsible Tree Panels =====");
        if (ImGui::CollapsingHeader("Collapsible Panel – Click to expand"))
        {
            ImGui::Text("Inner panel content");
            ImGui::Button("Panel Inner Button");
        }
        if (ImGui::TreeNode("Tree Node"))
        {
            ImGui::BulletText("Sub-item 1");
            ImGui::BulletText("Sub-item 2");
            ImGui::TreePop();
        }
        ImGui::Spacing();

        // ========== 11. Tab Bar ==========
        ImGui::Text("===== Tabs / TabBar =====");
        ImGui::BeginTabBar("TabBar");
        if (ImGui::BeginTabItem("Tab 1"))
        {
            ImGui::Text("Content for Tab 1");
            ImGui::EndTabItem();
        }
        if (ImGui::BeginTabItem("Tab 2"))
        {
            ImGui::Text("Content for Tab 2");
            ImGui::EndTabItem();
        }
        ImGui::EndTabBar();
        ImGui::Spacing();

        // ========== 12. Table Widget ==========
        ImGui::Text("===== Table Widget =====");
        if (ImGui::BeginTable("table1", 3, ImGuiTableFlags_Borders))
        {
            ImGui::TableSetupColumn("ID");
            ImGui::TableSetupColumn("Name");
            ImGui::TableSetupColumn("Value");
            ImGui::TableHeadersRow();

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

        // ========== 13. Right-Click Context Menu ==========
        ImGui::Text("===== Right-Click Menu (Right click this text) =====");
        if (ImGui::IsItemClicked(ImGuiMouseButton_Right))
            ImGui::OpenPopup("RightMenu");
        if (ImGui::BeginPopup("RightMenu"))
        {
            ImGui::MenuItem("Context Item 1");
            ImGui::MenuItem("Context Item 2");
            ImGui::Separator();
            ImGui::MenuItem("Close Menu");
            ImGui::EndPopup();
        }
        ImGui::Spacing();

        // ========== 14. Non-Modal Popup Window ==========
        if (showPopupWin)
        {
            ImGui::OpenPopup("PopupWindow");
            showPopupWin = false;
        }
        if (ImGui::BeginPopup("PopupWindow"))
        {
            ImGui::Text("Non-modal popup, main window still interactable");
            if (ImGui::Button("Close Popup"))
                ImGui::CloseCurrentPopup();
            ImGui::EndPopup();
        }

        // ========== 15. Modal Dialog ==========
        if (ImGui::Button("Open Modal Dialog"))
            showModal = true;
        if (showModal)
        {
            ImGui::OpenPopup("ModalDialog");
            showModal = false;
        }
        if (ImGui::BeginPopupModal("Modal Dialog", nullptr, ImGuiWindowFlags_AlwaysAutoResize))
        {
            ImGui::Text("Modal locks main window; you must close it first");
            if (ImGui::Button("OK", 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)

You can slowly experiment and learn the usage of each widget.

The widget library is very comprehensive and fully meets the needs of simple utility software development. It includes collapsible trees, tab pages, all form controls: single/multi-line text boxes, radio buttons, checkboxes, dropdown combos, progress bars, collapsible panels, tables, right-click menus, color pickers and more. Feel free to test them by yourself.

Leave a Reply

Your email address will not be published. Required fields are marked *