Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

What do QAction::setMenu?



  • From doc
    Sets the menu contained by this action to the specified menu.

    I have next code:

        ui->setupUi(this);
        menubar = new QMenuBar(this);
        act1 = new QAction("action 1", this);
        act2 = new QAction("action 2", this);
        QMenu *menu = new QMenu("menu", this);
        menu->addAction("mmm");
        menu->addAction("nnn");
    //    act1->setMenu(menu);
        menubar->addAction(act1);
        menubar->addAction(act2);
        menubar->addMenu(menu);
    

    and I get next result

    But if I uncomment

    act1->setMenu(menu);
    

    I have another result

    I don't understand what's going on.


  • Moderators

    It's a little hard to see when you use the menu bar like that, but here's what's going on:

    With the line commented out you are creating the following structure (your first picture):

    | act1 | act2 | menuAct|
                    mmm
                    nnn
    

    menuAct is an action automatically generated for the menu.
    Now when you uncomment the line a couple of things come to play.
    First it's important to know that an action can only be placed on a menu bar once. If you add it second time it will be removed from its previous place. For example:

    menubar->addAction(act1);
    menubar->addAction(act2);
    menubar->addAction(act1);
    

    will create a menu bar like this:

    | act2 | act1 |
    

    Second thing is that when you add a menu to an action that action becomes the menu's menuAction.
    Last piece of the puzzle is that when you put a menu on a menu bar its menuAction is placed on the menu bar to trigger that menu. If the menu has no action associated with it one is created for you.

    So, having these three pieces of information, we can follow what's going on:

    menu->addAction("mmm");    // action mmm is added to menu
    menu->addAction("nnn");    // action nnn is added to menu
    act1->setMenu(menu);       // added menu to act1, act1 becomes menu's menuAction
    menubar->addAction(act1);  // act1 is added to menubar
    menubar->addAction(act2);  // act2 is added to menubar
    menubar->addMenu(menu);    // menu's menuAction is added to menubar. Because it is act1 it is first taken out of the previous place on menubar
    

    So the resulting structure is now (your second picture):

    |  act2 | act1 |
              mmm
              nnn
    

Log in to reply