当未触发其QAction之一时,阻止QMenu关闭

时间:2017-01-10 08:50:41

标签: c++ qt qt4 qmenu qaction

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

1 个答案:

答案 0 :(得分:1)

如图所示使用信号阻断器:

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

};