简体   繁体   中英

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM