Pop-up menu

TGUI does not yet support right click events or has a Pop-up Menu. However, the menu itself does not has to be anything more than a ListBox and it takes only a small effort to show and hide it on events. So below you can find the code needed to implement a Pop-up menu in your own code.

Note that this example uses the optional unbound parameter feature of the connect function, it will not compile on VS2013.

#include <TGUI/TGUI.hpp>

tgui::ListBox::Ptr popumMenu;

// Called when selecting an item in the pop-up menu
void popupMenuCallback(std::string item)
{
    std::cout << item << std::endl;
}

void rightClickCallback(tgui::Gui& gui, sf::Vector2f position)
{
    popumMenu = tgui::ListBox::create();
    popumMenu->addItem("Option 1");
    popumMenu->addItem("Option 2");
    popumMenu->addItem("Option 3");
    popumMenu->addItem("Option 4");
    popumMenu->setItemHeight(20);
    popumMenu->setPosition(position);
    popumMenu->setSize(120, popumMenu->getItemHeight() * popumMenu->getItemCount());
    popumMenu->connect("ItemSelected", popupMenuCallback);
    gui.add(popumMenu);
}

int main()
{
    sf::RenderWindow window(sf::VideoMode(800, 600), "TGUI window");
    tgui::Gui gui(window);
    gui.setFont("TGUI/fonts/DejaVuSans.ttf");

    while(window.isOpen())
    {
        sf::Event event;
        while(window.pollEvent(event))
        {
            if(event.type == sf::Event::Closed)
                window.close();

            // Check if there is a pop-up menu
            if (popumMenu)
            {
                // When mouse is released, remove the pop-up menu
                if (event.type == sf::Event::MouseButtonReleased && event.mouseButton.button == sf::Mouse::Left)
                {
                    gui.remove(popumMenu);
                    popumMenu = nullptr;
                }

                // When mouse is pressed, remove the pop-up menu only when the mouse is not on top of the menu
                if (event.type == sf::Event::MouseButtonPressed)
                {
                    if (!popumMenu->mouseOnWidget(event.mouseButton.x, event.mouseButton.y))
                    {
                        gui.remove(popumMenu);
                        popumMenu = nullptr;
                    }
                }
            }

            // Perhaps we have to open a menu
            else if (event.type == sf::Event::MouseButtonPressed && event.mouseButton.button == sf::Mouse::Right)
            {
                rightClickCallback(gui, sf::Vector2f(event.mouseButton.x, event.mouseButton.y));
            }

            gui.handleEvent(event);
        }

        window.clear();
        gui.draw();
        window.display();
    }
}