防止 QMenu 在其 QAction 之一未被触发时关闭

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

我有一个 QMenu 和几个带有复选框的 QWidgetActions,当我尝试单击 QMenu 的任何区域时,菜单关闭。我想阻止这种情况。

以下是我执行操作和菜单的方式。

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);

如图所示使用信号拦截器:

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);
    }

};