Search code examples
qtmenuqmenu

Qt almost same main menu entries


I'm using c++ Qt library and I want to do something which would do :

connect(actionB11, SIGNAL(triggered()), this, SLOT(SetSomething(1, 1)));
connect(actionB12, SIGNAL(triggered()), this, SLOT(SetSomething(1, 2)));
connect(actionB21, SIGNAL(triggered()), this, SLOT(SetSomething(2, 1)));
connect(actionB22, SIGNAL(triggered()), this, SLOT(SetSomething(2, 2)));

The code above doesnt work because SIGNAL function has to have same number and argument types as SLOT function.

Does exist a way how to do it? I dont want to have about 20 function as SetSomething11, SetSomething12 calling SetSomething(1, 1) etc.


Solution

  • In situations like this you have three simple options:

    1. connect each QAction to its own slot (not good)
    2. use a QSignalMapper
    3. add each QAction to a QActionGroup and use the QActionGroup::triggered(QAction*) signal, coupled with setting each QAction's data (see QAction::setData() and QAction::data())

    When you set the data for a QAction, you can only store one QVariant (i.e., one value). So if you want two values, I would recommend just creating a simple mapping, like this:

    void Window::onActionGroupTriggered(QAction *action);
    {
        int i = action->data().toInt();
        int a, b;
        a = i / 10;
        b = i - 10;
        setSomething(a, b); // for example if i = 15, then a = 1 and b = 5
    }