A ListView of checkboxes in PyQt

Eli Bendersky picture Eli Bendersky · May 11, 2009 · Viewed 23.4k times · Source

I want to display a QListView where each item is a checkbox with some label. The checkboxes should be visible at all times. One way I can think of is using a custom delegate and QAbstractListModel. Are there simpler ways? Can you provide the simplest snippet that does this?

Thanks in advance

Answer

Eli Bendersky picture Eli Bendersky · May 13, 2009

I ended up using the method provided by David Boddie in the PyQt mailing list. Here's a working snippet based on his code:

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
from random import randint


app = QApplication(sys.argv)

model = QStandardItemModel()

for n in range(10):                   
    item = QStandardItem('Item %s' % randint(1, 100))
    check = Qt.Checked if randint(0, 1) == 1 else Qt.Unchecked
    item.setCheckState(check)
    item.setCheckable(True)
    model.appendRow(item)


view = QListView()
view.setModel(model)

view.show()
app.exec_()

Note: changed the call of setData with a check role to setCheckState and used setCheckable instead of flags.