[Solved] Customize QMenu Programmatically



  • Hi,

    My application run on two modes and according to the mode changes I need to customize QMenu.

    I used following steps.

    Create 6 actions using Design Mode of Qt creator.

    Add action_1 and action_2 graphically to view_menu.

    Then programmatically set other four actions as below.

    @if(mode==mode_1)
    {
    ui->view_menu->addActions(modeOneActions());
    }
    else if (mode==mode_2)
    {
    ui->view_menu->addActions(modeTwoActions());
    }@

    @QList<QAction *> modeOneActions()
    {
    QList<QAction *> actionslist;
    actionslist.append(ui->action_3);
    actionslist.append(ui->view_menu->addSeparator());
    actionslist.append(ui->action_4);
    return actionslist;
    }@

    @QList<QAction *> modeTwoActions()
    {
    QList<QAction *> actionslist;
    actionslist.append(ui->view_menu->addSeparator());
    actionslist.append(ui->action_5);
    actionslist.append(ui->action_6);
    return actionslist;
    }@

    But this way can not remove the previously added actions. If go to mode_2 after mode_1 , then all actions displayed in view_menu of mode_2.

    I found that I can clear() all the items from view_menu and add particular one. But it is not simple. (have more actions)

    Dear friends, I have two questions.

    1. Are there any methods?
    2. Is the correct way to add seperators?
      @actionslist.append(ui->view_menu->addSeparator());@


  • QMenu::clear() empties the menu.



  • You could also hide the actions you don't want to use in your mode instead. That way they are still added to the menu, just not visible.



  • Thank you friends. It sounds like I should remove all and add them again or I should add all and hide some of them according to the mode.

    Thanks again.



  • Did you even try the QAction::setVisible I suggested?



  • Andre,

    I created three methods as
    @QList<QAction *> commonActions();
    QList<QAction *> modeOneActions();
    QList<QAction *> modeTwoActions();@

    When change the modes I clear all the actions and add the suitable actions with common actions.


Log in to reply
 

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