Uneditable QListView
Asked Answered
O

5

23

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)
Omdurman answered 3/6, 2011 at 10:55 Comment(0)
E
49

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.

Edme answered 3/6, 2011 at 14:46 Comment(2)
This is more of a hack as it will still be editable, just not through this particular view.Selfreliance
listView.setEditTriggers(QAbstractItemView::NoEditTriggers); for C++ qtSickert
O
2

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.

Omdurman answered 5/6, 2011 at 17:29 Comment(1)
Using QListWidget is a great solutionTrichotomy
S
0

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

Selfreliance answered 4/6, 2011 at 9:8 Comment(2)
The link is brokenXylidine
Archived link from 2011 here: web.archive.org/web/20110807124820/http://doc.qt.nokia.com/…Idden
U
0

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.

Unlawful answered 3/4, 2019 at 20:19 Comment(0)
B
0

In PySide6,

from PySide6.QtWidgets import QListView, QAbstractItemView
...

self.listview = QListView()
self.listview.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
Butcherbird answered 11/4 at 6:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.