Search code examples
c++popupimgui

ImGUI Popup not showing up but executing the code


I am making a program using ImGui and I want to display a PopUp if the input on one window is bad after clicking the button "OK". It enter the IF statement and execute the code but the popup doesnt show up.

ImGui::OpenPopup("Error Creating Image");
// Always center this window when appearing
ImVec2 center = ImGui::GetMainViewport()->GetCenter();
ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
                
if (ImGui::BeginPopupModal("Error Creating Image", NULL, ImGuiWindowFlags_AlwaysAutoResize)) {
    ImGui::SetItemDefaultFocus();
    ImGui::Text("The size of the Image must be greater than 0. Also it need to have a name!\n\n");

        ImGui::Separator();

    if (ImGui::Button("OK")) {
        ImGui::CloseCurrentPopup();
    }
    ImGui::EndPopup();
}

Solution

  • Does the entire code you are showing only run once, when the error occured?

    The ImGui::BeginPopupModal and the associated if block has to run every frame, otherwise the popup won't get drawn. Something like this:

    void foo() {  // 'foo' runs every frame.
        if (ImGui::Button("Show popup"))
            ImGui::OpenPopup("ThePopup");
    
        // Maybe some other stuff here.
    
        if (ImGui::BeginPopupModal("ThePopup")) {
            // Draw popup contents.
            ImGui::EndPopup();
        }
    }
    

    The code for drawing the popup can be moved anywhere, as long as it's on the same level of the ID stack.