0
#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();
}

When I activate a QTreeWidget's item by pressing Enter, nested dialog is created and it immediately presses button inside of it. How do I get rid of it?

equeim
  • 107
  • 10

1 Answers1

0

I solved this by overriding keyPressEvent of the QTreeView that was inside the dialog:

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

This way pressing Enter key inside QTreeView doesn't passes to its parent.

equeim
  • 107
  • 10