Home > Software engineering >  Get clicked item on QTreeWidget
Get clicked item on QTreeWidget

Time:10-31

class TreeWidget : public QTreeWidget
{
    Q_OBJECT

public:    

    TreeWidget(QWidget* parent = 0) : QTreeWidget(parent) 
    {
        connect(this, &QTreeWidget::itemClicked, this, &TreeWidget::onItemClicked);
    }


public slots:
    void onItemClicked(QTreeWidgetItem* item, int column)
    {
        auto _item = dynamic_cast<QTreeWidgetItem*>(item);
        qDebug() << "item: " << item << " _item: << _item;
        // if (item == 0) { ... }
        // elseif ...
    }
}

I'm confused about how to get the clicked item of a QTreeWidget, in my example, qDebug() prints something like item: 0x2a64e3edfb0 what is the 'proper' way to read it?

I'm trying to perform different actions according to the item clicked.

CodePudding user response:

In your code item: 0x2a64e3edfb0 is your object and 0x2a64e3edfb0 is your object's address in memory.

But your QTreeWidgetItem object has functions and properties like its text and you can get it like this:

void MainWindow::on_treeWidget_itemClicked(QTreeWidgetItem *item, int column)
{

    qDebug() << "item: " << item <<","<<item->text(column);


}

For get the Index of QTreeWidgetItem you should get it from your parent means QTreeWidget

like this :

void MainWindow::on_treeWidget_itemClicked(QTreeWidgetItem *item, int column)
{

    qDebug() << "item: " <<ui->treeWidget->indexOfTopLevelItem(item);

}

the output :

enter image description here

If item is a child of a branch then you can use this:

 qDebug() << "item: " <<ui->treeWidget->indexFromItem(item,column).row();

Look at QTreeWidget::indexFromItem function.

  •  Tags:  
  • c qt
  • Related