QWidgetAction在触发()后保持可见。

问题描述 投票:3回答:1

我有一个QWidgetAction,它拥有一个由QLineEdit和QPushButton组成的QWidget。一旦用户按下按钮,QWidgetAction就会调用触发槽。

现在我有一个QMenu,我用exec.Action激活它。问题是即使触发器被调用了(我已经把它连接到一个打印函数来检查),菜单也不会关闭。

常规的QActions工作良好。

有什么原因吗?

P.S. 我在谷歌上搜索这个问题时,发现了以下内容 横跨 同样的问题,但没有解决方案。

c++ python qt pyqt
1个回答
0
投票

多年的老问题,但我仍然有一个答案,希望它能帮助任何人!

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

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

© www.soinside.com 2019 - 2024. All rights reserved.