2
votes

I am using C++/Qt 5.5 and in my software, I want the Qt::Key_Space to trigger the opening of a menu, and the same button, to trigger the closing of the same menu. The problem is that if I implement it as:

this->button = new QPushButton();
this->button->setShortcut( QKeySequence( Qt::Key_Space ) );
connect(this->button, &QPushButton::clicked, this, &MenuClass::startMenuButtonClicked);

...

    this->in_menu_button = new QPushButton();
    this->in_menu_button->setShortcut( QKeySequence( Qt::Key_Space ) );
    connect(this->in_menu_button, &QPushButton::clicked, this, &InTheMenuClass::startMenuButtonClicked);

If i do it like this, only one way to the menu works. Do you have any ideas on how to solve this issue?

2

2 Answers

1
votes

You need to create only one button and assign the shortcut to it. Then depending on the state of the menu (open/close) perform an opposite action in the button's handler.

0
votes

I solved it using a state machine. I created an enumaration with 2 states and made a static instance of it.

public:
    enum STATE {MAIN_WINDOW, MENU};
    static STATE state;

Then, i initialized it by default to have the MAIN_WINDOW state.

MyClass::STATE MyClass::state = STATE::MAIN_WINDOW;

Then, I connected both slots of the shortcuts for both buttons to call the same slot which checks and sets the current state.

QShortcut * shortcut = new QShortcut( QKeySequence( Qt::Key_Space ), back_to_main );
connect( shortcut, &QShortcut::activated, this, &MyClass::checkState);

QShortcut * shortcut = new QShortcut( QKeySequence( Qt::Key_Space ), go_to_menu );
connect( shortcut, &QShortcut::activated, this, &MyClass::checkState);

void MyClass::checkState()
{
    if (MyClass::state == MyClass::MAIN_WINDOW )
    {
        MyClass::goToMenu();
        MyClass::state = MyClass::STATE::MENU;
    }
    else if ( MyClass::state == MyClass::MENU )
    {
        MyClass::goBackToMain();
        MyClass::state = MyClass::STATE::MAIN_APP;
    }
}

*MyClass can be any class.