2

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

1 回答 1

2

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

};
于 2017-01-10T15:35:10.087 回答