简体   繁体   中英

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

I have a QMenu and Several QWidgetActions, with checkboxes, when I try to click on any area of the QMenu, the menu get closed. I would like to prevent that.

Here is how I do the actions and the menus.

QWidgetAction* action = new QWidgetAction(menu);
action->setCheckable(checkable);
action->setData(data);    

QWidget *containerWidget = new QWidget(menu);
QHBoxLayout *hbox = new QHBoxLayout(containerWidget);
QCheckBox *checkBox = new QCheckBox(menu);
checkBox->setText(title);
QObject::connect(checkBox, &QCheckBox::toggled, action, &QAction::trigger);

hbox->addWidget(checkBox);
hbox->addWidget(widget);

QObject::connect(action, &QAction::toggled, [this]() { OnPoiFilterCheckBox(); });
containerWidget->setLayout(hbox);

action->setDefaultWidget(containerWidget);
action->setData(data);
menu->addAction(action);

Use a signal blocker as shown:

class filter_menu : public QMenu
{
    Q_OBJECT
public:
    filter_menu(QWidget *parent = 0) : QMenu(parent) {}

    virtual void mouseReleaseEvent(QMouseEvent *e)
    {
        QAction *action = activeAction();
        if (action && action->isEnabled()) {
            QSignalBlocker blocker(action);
            action->setEnabled(false);
            QMenu::mouseReleaseEvent(e);
            action->setEnabled(true);

        }
        else
            QMenu::mouseReleaseEvent(e);
    }

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM