PyQT -- How can you make a QTreeview uneditable but also selectable?
Asked Answered
W

1

11

I just switched from wxPython to PyQT and I am having some trouble with the QTreeview. I have a QTreeview that will display data categorized into sections that are expandable, but the data in this TreeView should not be editable, but I need to be able to have the user select the data (doubleclicking is going to execute another method). I am not certain how to make it readonly but also selectable. I am using the QStandardItemModel with the QStandardItem to hold the data.

Any help would be much appreciated.

Waiwaif answered 26/4, 2014 at 0:59 Comment(0)
T
21

You can set individual items to be uneditable by doing this when you create the QSandardItem

item = QStandardItem('my_item_text')
item.setEditable(False)

You can disable editing for the entire treeview by calling

my_treeview.setEditTriggers(QAbstractItemView.NoEditTriggers)

By default the treeview should allow you to select items, but if you want to change the default behaviour you will want to look at the setSelectionMode() and setSelectionBehavior() methods of the treeview (well they are for QAbstractItemView which QTreeView inherits from). c++ documentation for these methods can be found here which I generally use over the PyQt documentation as it is often more complete, and it isn't too difficult to translate into Python code. Just replace all instances of :: with .)

Trichite answered 26/4, 2014 at 1:13 Comment(2)
Thanks for the quick response! This worked just liked I needed it to. I also found that you can do something like this 'item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)' and it will give you the same behavior. But the disabling of editing for the whole treeview at once is better.Waiwaif
No problem! I'm pretty sure item.setEditable() wraps item.setFlags() at the low level, but without overwriting the existing set of flags that don't relate to editing.Trichite

© 2022 - 2024 — McMap. All rights reserved.