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

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
artomason
  • 3,625
  • 5
  • 20
  • 43

2 Answers2

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)
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • that works perfectly for getting the text, is it also possible to pull the index? Thanks! – artomason Dec 03 '17 at 17:44
  • @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. – eyllanesc Dec 03 '17 at 17:46
  • @AaronTomason In a QTreeView to which index you refer, since this is relative to the parent. – eyllanesc Dec 03 '17 at 17:48
  • I wasn't sure if that was a either / or type situation. – artomason Dec 03 '17 at 17:50
  • 1
    @AaronTomason Read this: http://doc.qt.io/qt-5/model-view-programming.html#model-classes – eyllanesc Dec 03 '17 at 17:52
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

hellohawaii
  • 3,074
  • 6
  • 21