Sections

I would like to detect if the expansion sign has been clicked in my QTreeView. How can this be achieved?

 

Answer:

If you want to be notified when the user clicks the expansion button for the items in your tree, then you can reimplement the mousePressEvent() and calculate the position of the expansion sign. If the mouse is over the calculated position, then you can for example emit a signal to notify it and do your own handling. Otherwise, simply call the base implementation.


The following example demonstrates how this can be done:

#include <QtGui>

class TreeWidget : public QTreeWidget
{
public:
    TreeWidget()
    {
        setColumnCount(1);
        item1 = new QTreeWidgetItem(this);
        item1->setText(0, "item 1");
        item1->setExpanded(true);
        
        item2 = new QTreeWidgetItem(item1);
        item2->setText(0, "item 2");
        item2->setExpanded(true);
        item3 = new QTreeWidgetItem(item2);
        item3->setText(0, "item 3");
        item4 = new QTreeWidgetItem(item1);
        item4->setText(0, "item 4");
    }
    void mousePressEvent(QMouseEvent *event)
    {
        QModelIndex indexClicked = indexAt(event->pos());
        if(indexClicked.isValid())
        {
            QRect vrect = visualRect(indexClicked);
            int itemIndentation = vrect.x() - visualRect(rootIndex()).x();
            
            QRect rect = QRect(header()->sectionViewportPosition(0) + itemIndentation - 
                indentation(), vrect.y(), indentation(), vrect.height());
            
            if(rect.contains(event->pos()) && model()->hasChildren(indexClicked)) {
                qDebug() << "plus clicked";
                QTreeWidget::mousePressEvent(event);
                return;
            } else {
                QTreeWidget::mousePressEvent(event);
            }
        }
    }
private:
    QTreeWidgetItem *item1;
    QTreeWidgetItem *item2;
    QTreeWidgetItem *item3;
    QTreeWidgetItem *item4;
};

int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    TreeWidget box;
    box.show();
    return app.exec();    
}

back

Patron of KDECustomers

Customers