Get the text and index of the current selected QTreeView item
Asked Answered
M

2

5

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

Malaria answered 3/12, 2017 at 17:20 Comment(0)
F
10

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)
Franchescafranchise answered 3/12, 2017 at 17:38 Comment(5)
that works perfectly for getting the text, is it also possible to pull the index? Thanks!Malaria
@AaronTomason What do you mean by index, I tell you that this depends on the model, if you do not know how to do it, create another question indicating your model, and an example of how you fill it. On the other hand if my answer solved your problem do not forget to mark it as correct.Franchescafranchise
@AaronTomason In a QTreeView to which index you refer, since this is relative to the parent.Franchescafranchise
I wasn't sure if that was a either / or type situation.Malaria
@AaronTomason Read this: doc.qt.io/qt-5/model-view-programming.html#model-classesFranchescafranchise
S
0

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

Swamp answered 19/4, 2022 at 18:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.