Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A ListView of checkboxes in PyQt

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

like image 268
Eli Bendersky Avatar asked May 11 '09 04:05

Eli Bendersky


1 Answers

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.

like image 53
Eli Bendersky Avatar answered Sep 28 '22 19:09

Eli Bendersky