Prevent a QMenu from closing when one of its QAction is triggered

前端 未结 6 1855
北荒
北荒 2020-12-15 06:30

I\'m using a QMenu as context menu. This menu is filled with QActions. One of these QActions is checkable, and I\'d like to be able to check/uncheck it without closing the c

6条回答
  •  囚心锁ツ
    2020-12-15 07:22

    This is my solution:

        // this menu don't hide, if action in actions_with_showed_menu is chosen.
        class showed_menu : public QMenu
        {
          Q_OBJECT
        public:
          showed_menu (QWidget *parent = 0) : QMenu (parent) { is_ignore_hide = false; }
          showed_menu (const QString &title, QWidget *parent = 0) : QMenu (title, parent) { is_ignore_hide = false; }
          void add_action_with_showed_menu (const QAction *action) { actions_with_showed_menu.insert (action); }
    
          virtual void setVisible (bool visible)
          {
            if (is_ignore_hide)
              {
                is_ignore_hide = false;
                return;
              }
            QMenu::setVisible (visible);
          }
    
          virtual void mouseReleaseEvent (QMouseEvent *e)
          {
            const QAction *action = actionAt (e->pos ());
            if (action)
              if (actions_with_showed_menu.contains (action))
                is_ignore_hide = true;
            QMenu::mouseReleaseEvent (e);
          }
        private:
          // clicking on this actions don't close menu 
          QSet  actions_with_showed_menu;
          bool is_ignore_hide;
        };
    
        showed_menu *menu = new showed_menu ();
        QAction *action = menu->addAction (new QAction (menu));
        menu->add_action_with_showed_menu (action);
    

提交回复
热议问题