Important: Please read the Qt Code of Conduct -

[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.

    else if (mode==mode_2)

    @QList<QAction *> modeOneActions()
    QList<QAction *> actionslist;
    return actionslist;

    @QList<QAction *> modeTwoActions()
    QList<QAction *> actionslist;
    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?

  • 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