我有一个QWidgetAction,它包含由QLineEdit和QPushButton组成的QWidget。用户按下按钮后,QWidgetAction将调用触发器插槽。

现在,我有了一个用exec激活的QMenu。问题是即使调用触发器(我也将其连接到打印功能以进行检查),菜单也不会关闭。

常规的QAction效果很好。

知道为什么吗?

附言谷歌搜索这个问题,我来到across people with同样的问题,但没有解决方案。

最佳答案

岁的问题,但我仍然有一个答案,希望它可以帮助任何人!

我将描述我的完整解决方案,该解决方案不仅隐藏菜单,而且还管理视觉表示。

QWidgetAction子类:MyClass.h

class MyClass : public QWidgetAction {
    Q_OBJECT
public:
    MyClass(QObject* parent);
    bool eventFilter(QObject*, QEvent*) override;

signals:
    void mouseInside();
    void mouseOutside();

protected:
    QWidget* createWidget(QWidget* parent) override;

private:
    QWidget* w;
    QWidget* border;
    QFormLayout *form;
    QHBoxLayout *mainLayout;
}

QWidgetAction子类MyClass.cpp
QWidget* MyClass::createWidget(QWidget* parent) {
    w          = new QWidget(parent);
    border     = new QWidget(parent);
    mainLayout = new QHBoxLayout(w);
    layout     = new QFormLayout();
    border->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Maximum));
    border->setMaximumWidth(10);
    border->setMinimumWidth(10);
    border->setMaximumHeight(1000); //Anything will do but it needs a height
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->setSpacing(0);
    w->setLayout(mainLayout);
    mainLayout->addWidget(border);
    mainLayout->addLayout(layout);
    layout->setContentsMargins(6, 11, 11, 11);
    layout->setSpacing(6);
    // Insert your widgets here, I used a QFormLayout
    QLineEdit *l = new QLineEdit(w);
    form->addRow("Test", l);
    // I added a button to accept input
    QPushButton* b = new QPushButton("Send", w);
    connect(b, SIGNAL(clicked()), this, SLOT(trigger()));
    layout->addWidget(b);
    w->installEventFilter(this); // This is to avoid non button clicks to close the menu
    return w;
}

bool MyClass::eventFilter(QObject*, QEvent* ev) {
    if (ev->type() == QEvent::MouseButtonPress
        || ev->type() == QEvent::MouseButtonDblClick
        || ev->type() == QEvent::MouseButtonRelease) {
        return true;
    } else if (ev->type() == QEvent::Enter) {
        border->setStyleSheet("background-color: #90c8f6;");
        emit mouseInside();
    } else if (ev->type() == QEvent::Leave) {
        border->setStyleSheet("");
        emit mouseOutside();
    }
    return false;
}

最后,将QWidgetAction插入菜单中,在代码中添加以下内容:
QMenu *m = new QMenu(this);
MyClass *item = new MyClass(m);
connect(item, &QAction::triggered, [=] { m->hide(); YOUR CODE HERE}); // Add your action here

// This is to give a visual cue to your item, while deselecting the stuck
// action which was previously selected
connect(item, &MyClass::mouseInside, [=] { m->setActiveAction(nullptr); });
ui->yourButton->setMenu(m);
m->addAction(item);

关于c++ - QWidgetAction在trigger()之后保持可见,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2873106/

10-09 03:35