artomason
artomason

Reputation: 3993

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

Upvotes: 5

Views: 12908

Answers (2)

hellohawaii
hellohawaii

Reputation: 3074

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

Upvotes: 0

eyllanesc
eyllanesc

Reputation: 243897

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)

Upvotes: 11

Related Questions