Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select row and column in pyqt QTreeView

Tags:

python

pyqt

pyqt4

I have a filter on qtreeview that recreates the rows and columns. Once the filter is removed of all text. ie filter = "". The qtreeview is recreated. I am looking to preselect a row when the qtreeview is recreated based on the selection when the user's filtered results.

I know that method I should be using is: tree.setCurrentIndex(m)

I know that m should be: m = QtCore.QModelIndex()

But, I can't seem to set the row and column in the QModelIndex that setCurrentIndex is happy with.

I know the selected item by text. Planning on getting the row index while the qtreeview is being recreated.

The qtreeview is setup like:

  • a
    • 0
    • 1
  • b
    • 2
    • 3
  • c
    • 4
    • 5
like image 295
Nachtwache Avatar asked Jan 24 '26 09:01

Nachtwache


1 Answers

Columns don't work how you would expect.

In your example, you do not have any columns, just rows.

To access item a, you should do the following:

>>> # setting up the model
>>> tree = QtGui.QTreeView()
>>> model = QtGui.QStandardItemModel()
>>> tree.setModel(model)

>>> # accessing data
>>> # To get item "a"
>>> a = tree.model().index(0, 0)
>>> a
<PySide.QtCore.QModelIndex(0,0,0x5805c40,QStandardItemModel(0x5805b30) )   at 0x7f9a81720148>
>>>
>> # to get item "a, 0"
>>> a0 = a.child(0, 0)
>>> a0
<PySide.QtCore.QModelIndex(0,0,0x7f9a88013d30,QStandardItemModel(0x5805b30) )   at 0x7f9a81720348>

Remember, that everything in Qt follows a parent/child relationship, including the QTreeView. If this model seems fairly slow to you, you can look at providing methods to facilitate this for you (do not look at Qt for help, since QProxyModel has been depricated and should not be used.

In short, item a is a child of the model at (0, 0). Item b is at (1, 0), and so forth. The children of item a can be referenced from a, using a.child(row, column). Child 0 is at (0, 0) and child 1 is at (1, 0).

like image 193
Alexander Huszagh Avatar answered Jan 26 '26 00:01

Alexander Huszagh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!