Search code examples
qtexpandqtreeviewqtreewidget

How to redefine a node expanding in a QTreeWidget?


The way I understand the qtreeview.cpp the expand method in the QTreeView is responsible for expanding nodes. For example it is used in the expandOrCollapseItemAtPos method. I try to redefine a node expansion in the QTreeWidget:

#include <QApplication>
#include <QWidget>
#include <QTreeWidget>
#include <QMessageBox>

class MyTree : public QTreeWidget
{
public:
    MyTree(QWidget *parent) : QTreeWidget(parent) {}
    expandItem(const QTreeWidgetItem *item) {
        QMessageBox msg;
        msg.setText("EXPAND ITEM!!");
        msg.exec();
        QTreeWidget::expandItem(item);
    }
    expand(const QModelIndex &index) {
        QMessageBox msg;
        msg.setText("EXPAND!!");
        msg.exec();
        QTreeWidget::expand(index);
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QWidget *mainWidget = new QWidget();
    mainWidget->resize(200,100);

    MyTree *myTree = new MyTree(mainWidget);
    myTree->resize(200,100);

    QTreeWidgetItem *node, *leaf;
    node = new QTreeWidgetItem(myTree);
    node->setText(0,"node");
    leaf = new QTreeWidgetItem(node);
    leaf->setText(0,"leaf");

    mainWidget->show();
    return a.exec();
}

But there is no any message box when I expand a node. I tried to comment QTreeWidget::expandItem(item); and QTreeWidget::expand(index); but expanding is still working. How do I redefine a node expanding in a QTreeWidget?


Solution

  • QTreeWidget::expand and QTreeWidget::expandItem are non-virtual methods. So redefinition is not useful. I will use slot-signal mechanism with QTreeWidget::expanded/collapsed signals.

    connect(this, SIGNAL(expanded(QModelIndex)), this, SLOT(myExpand(QModelIndex)));