嵌套的QDialog会自动在其中按下QPushButton

时间:2016-08-27 17:21:45

标签: c++ qt

#include <QApplication>
#include <QDebug>
#include <QDialog>
#include <QPushButton>
#include <QTreeWidget>
#include <QVBoxLayout>

int main(int argc, char** argv)
{
    QApplication app(argc, argv);

    QDialog dialog;
    QVBoxLayout layout(&dialog);

    QTreeWidget treeWidget;
    treeWidget.insertTopLevelItem(0, new QTreeWidgetItem(&treeWidget));
    QObject::connect(&treeWidget, &QTreeWidget::activated, [&treeWidget]() {
        auto secondDialog = new QDialog(&treeWidget);
        auto layout = new QVBoxLayout(secondDialog);
        auto button = new QPushButton();
        QObject::connect(button, &QPushButton::clicked, []() {
            qDebug() << "button clicked";
        });
        layout->addWidget(button);
        secondDialog->show();
    });
    layout.addWidget(&treeWidget);

    dialog.show();

    return app.exec();
}

当我按Enter键激活QTreeWidget的项目时,会创建嵌套对话框并立即按下其中的按钮。我该如何摆脱它?

1 个答案:

答案 0 :(得分:0)

我通过覆盖对话框内的QTreeView的keyPressEvent解决了这个问题:

    class EnterEatingTreeView : public BaseTreeView
    {
    public:
        explicit EnterEatingTreeView(QWidget* parent = nullptr)
            : BaseTreeView(parent)
        {

        }
    protected:
        void keyPressEvent(QKeyEvent* event) override
        {
            BaseTreeView::keyPressEvent(event);
            switch (event->key()) {
            case Qt::Key_Enter:
            case Qt::Key_Return:
                event->accept();
            }
        }
    };

这样在QTreeView中按Enter键就不会传递给它的父。