我有一个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);
}
};