开发者

Uneditable QListView

开发者 https://www.devze.com 2023-03-10 08:48 出处:网络
I have a QListView displaying a list of items but I don\'t want the items to be edited (Currently a double click on the item allows you to edit them).

I have a QListView displaying a list of items but I don't want the items to be edited (Currently a double click on the item allows you to edit them).

This is my Code:

self.listView = QListView()
self.model = QStringListModel([ "item1" , "item2" , "item3" ])
self.开发者_如何学运维listView.setModel( self.model )

self.layout = QGridLayout()  
self.layout.addWidget(self.listView, 0 , 0 )
self.setLayout(self.layout)


Adding the line:

self.listView.setEditTriggers(QAbstractItemView.NoEditTriggers)

should fix things for you.

QListView inherits QAbstractItemView which has the method setEditTriggers(). Other possible values for setEditTriggers are available in the docs.


Thanks for the responses. I ended up going with a QListWidget instead as it is not editable by default.

Though I also found if you give the QListView a mouse Double clicked event and set it to do something other than edit the QListView, it overrides the edit function so that works too.


If model will be attached to multiple views and you don't want it to be editable by any of them, you can subclass QStringListModel and override flags():

from PyQt5.QtCore import Qt

class UneditableStringListModel(QStringListModel):

    def flags(self, index):
        return Qt.ItemIsSelectable & Qt.ItemIsEnabled


listView = QListView()
model = UneditableStringListModel([ "item1" , "item2" , "item3" ])
listView.setModel(model)

Now the user will not be able to edit model from any view.


QStringListModel is by definition editable. You should subclass and provide the appropriate flags

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号