bauervision
bauervision

Reputation: 887

How to get Pointer to Index in QTreeWidget?

I have created a QTreeWidget, and populated it with struct data (myObj.name, myObj.DOB, myObj.age, etc).

When I select on an item in the widget, I need to grab the pointer data associated with that selection to display it elsewhere.

I create the list with pointers, I just need to figure out how to in turn retrieve those pointers when I select on the list.

Upvotes: 0

Views: 1843

Answers (3)

bauervision
bauervision

Reputation: 887

So I was able to achieve what I needed by using QMap.

QMap<QTreeWidgetItem*, myObject*> myMap_container;//declared in .h

And then in my cpp:

    void MainWindow::on_myTree_itemClicked(QTreeWidgetItem *item, int column){
       myObject* rowData = myMap_container[item];
}

From there I was able to access the entirety of my struct data which has been assigned like so:

cout << rowData.Name << endl;
cout << rowData.Age << endl;
cout << rowData.SSN<< endl;
cout << rowData.FavColor<< endl;

Upvotes: 1

Pavan Chandaka
Pavan Chandaka

Reputation: 12731

As I am seeing tree widget here and not Abstract Model,I guess you are using columns in your widget. For example your node has three columns :name( 0 column), DOB ( 1 column) and age (2 column).

If that is the case, the simple way is:

QList<QTreeWidgetItem *> QlistTreeWId = YourTree->selectedItems();

Check for the list size, if size exists, then

yourObject.name = QlistTreeWId [0].text(0); //name column.
yourObject.DOB= QlistTreeWId [0].text(1); //DOB column.
yourObject.age= QlistTreeWId [0].text(2); //Age column.

Hope this helps.

Upvotes: 0

MillerTime
MillerTime

Reputation: 61

To access the data within your QTreeWidget (or rather the predefined tree model that comes for free with QTreeWidget), you can utilise one of the signals that QTreeWidget emits upon user interaction. i.e. clicked(QModelIndex).

The QTreeWidget documentation lists all of the signals available: (http://doc.qt.io/qt-5/qtreewidget.html#details)

For example:

connect(this, SIGNAL(clicked(QModelIndex)), this, SLOT(print_item(QModelIndex)));

Where 'this' is of type QTreeWidget. (I have populated a number of QString items into my tree structure),

With the above connected Signal and Slot, a click on one of my tree items results in the following method being executed,

void MainWindow::print_item(QModelIndex index){

    qDebug()<<"Item :"<<index.data().toString();
} 

As you can see the parameter that the 'clicked' signal passes is a QModelIndex which I then use in my above method to access the data within my tree item.

Upvotes: 0

Related Questions