'Get the text and index of the current selected QTreeView item

I was wondering how I can return the text value, and index of a selected item in a QTreeView. I tried using:

self.TreeView.selectedIndexes()

but that returns a QModelIndex. I'm not exactly sure how to convert that to an integer value. Googling around, I haven't really found anything about getting the text value either. Any ideas?

Sorry if this is a basic knowledge question. I'm new to python, and self teaching. In java, most objects can be casted, but I'm not really sure how that works with QObjects in Python.

I'm currently using Python 3.6 and PyQt5



Solution 1:[1]

The answer depends on the model, but I think that you are using standard Qt models, so the solution is to use the Qt::DisplayRole role:

for ix in self.TreeView.selectedIndexes():
    text = ix.data(Qt.DisplayRole) # or ix.data()
    print(text)

Solution 2:[2]

For the QModelIndex, you can use the method row() and column() to get the row index and column index. Perhaps this is the integer 'index' that you refer to.

for ix in self.TreeView.selectedIndexes():
    text = ix.data(Qt.DisplayRole) # or ix.data()
    print(text)
    row_index = ix.row()
    print(column_index)
    column_index = ix.row()
    print(column_index)

You can refer to this https://doc.qt.io/qt-5/qmodelindex.html

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 eyllanesc
Solution 2 hellohawaii