Qt Designer and Menu Commands: single action for all menu items?

  • i want all menu bar item "actions" to go to one function, passing in a command ID or unique string, and from THERE dispatch the command. i'm porting an old application and i don't want to create a separate function for every menu item. there must be a way?

  • Moderators

    // Connect all your actions to your single handler (I'm using some placeholder names):
    connect(yourAction, &QAction::triggered, myHandler, &MyHandler::handleAction);
    // Then:
    void MyHandler::handleAction() {
        auto action = qobject_cast<QAction*>(QObject::sender())->text();
        if (action == "Save") {
          // do the saving
        } else if (action == "...") {
          // etc.

    Pseudo code of course, just to give you an idea. Each slot can call sender() method to get the sending object. In this case, you will get a pointer to your QAction. I've used checking QAction->text() to determine action, but in reality you should rather use data()/setData() to store custom values (an enum maybe?) and check against that.

    Of course, you should also check is qobjhect_cast<>() returned a valid pointer, before you call any methods on it.

    Hope it helps. If it's unclear - ask more :-) I've tried to shorten the example as much as possible, maybe I've overdone it a tad.

  • @sierdzio thank you so much!

    i can't figure out how to mark YOUR post as "the answer" so i'll mark this as the answer and refer to your post above, self-referentially, and redundantly!

  • okay so i'm back working on this, and have hit a wall.
    I wish to build my menus in Qt Designer, and set up the signal/slot connections there, but i wonder if this is not possible.

    Here's my code:
    0_1500226753333_Screen Shot 2017-07-16 at 9.54.07 AM.png

    I've added the menuHandler() slot i think with the correct signature.

    but when i look in the signal/slot editor, it's not listed:
    0_1500226792792_Screen Shot 2017-07-16 at 9.53.39 AM.png

    What am i missing? I saw this post but it's not possible to use the GUI "drag and drop" signal-slot connector on a menu ITEM because when you click the tool, the menu closes.

  • okay figger'd it out. wow, it's a bit non-intuitive, and the doc leaves a bit to be desired. but okay here it is:

    you go to the object browser, and right click the object derived from QMainWindow, and pick "Change Signals / Slots", then under the "Slots" list, click the "+" button, and add your slot. I thought it would be gleaned from my source code, but it doesn't work that way.

    Once you add the slot signature (with the same name as what's used in your source code), and you connect the action to it from the "Signals & Slots editor", when you run, the slot will be called when the action is triggered!

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.