2017-01-10 131 views
1

當我嘗試點擊QMenu的任何區域時,菜單關閉,我有一個QMenu和幾個QWidgetActions,帶有複選框。我想阻止這一點。當QMenu的某個QAction沒有被觸發時,阻止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

使用信號阻斷,如圖所示:

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

};