ocornut / imgui

Dear ImGui: Bloat-free Graphical User interface for C++ with minimal dependencies
MIT License
59.51k stars 10.14k forks source link

Set default tab in TabBar #7956

Closed sodamouse closed 1 week ago

sodamouse commented 1 week ago

Version/Branch of Dear ImGui:

Version 1.90, Branch: docking

Back-ends:

imgui_impl_glfw.cpp + imgui_impl_opengl3.cpp

Compiler, OS:

Windows 11 + MSVC 2022

Full config/build information:

No response

Details:

My Issue/Question:

I'm trying to figure out how to have a TabBar's tab be activated by default, but only from the moment my application first launches until the user changes tabs. I know that it is possible to use the ImGuiTabItemFlags_SetSelected to programmatically determine which tab is selected, and that there is a ImGuiCond_FirstUseEver flag for similar use-cases in other context, but I don't know how to combine the effects of the two.

Basically, at startup, I calculate an index which corresponds to which tab I want to be selected by default, but how do I achieve the "do this only once" effect without unselecting the tab in the process?

Screenshots/Video:

No response

Minimal, Complete and Verifiable Example code:


int activeTabIdx = 3;

if (ImGui::BeginTabBar("Months", TAB_BAR_FLAGS))
{
    if (ImGui::BeginTabItem(MONTH_NAMES[month], nullptr, ImGuiTabItemFlags_SetSelected)) // Set this flag on the 4th tab, but only until the user selects another tab.
    {
        // ...
    }
}
GamingMinds-DanielC commented 1 week ago

You do not need to specify ImGuiTabItemFlags_SetSelected every frame to keep a tab selected. This flag triggers tab selection, after the first frame you can specify 0 and the tab will remain selected. You just need to know when you want to trigger it. Here is an example that switches to the tab every time the containing window gets opened:

if (ImGui::BeginTabBar("Months", TAB_BAR_FLAGS))
{
    ImGuiTabItemFlags flags = ImGui::IsWindowAppearing() ? ImGuiTabItemFlags_SetSelected : ImGuiTabItemFlags_None;
    if (ImGui::BeginTabItem(MONTH_NAMES[month], nullptr, flags))
    {
        // ...
    }
}