触发器()后QWidgetAction保持可见

时间:2010-05-20 11:11:14

标签: c++ python qt pyqt

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

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

常规QActions运作良好。

知道为什么吗?

P.S。谷歌搜索这个问题我across people with遇到了同样的问题,但没有解决方案。

1 个答案:

答案 0 :(得分:0)

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

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

QWidgetAction子类:MyClass.h

Release

QWidgetAction子类MyClass.cpp

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插入菜单中,在代码中添加以下内容:

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