10

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

Marc Mutz - mmutz
  • 24,485
  • 12
  • 80
  • 90
Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412

2 Answers2

24

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.

Community
  • 1
  • 1
Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
  • 1
    what signals (if any) are emitted when such item/checkbox is toggled? – marcin Jul 22 '15 at 18:03
  • 5
    to answer myself, `model.itemChanged` can be used, as shown here: http://www.pythoncentral.io/pyside-pyqt-tutorial-qlistview-and-qstandarditemmodel/ – marcin Jul 22 '15 at 18:30
  • what signals (if any) are emitted when such item/checkbox is highlight but no toggled? – grand Jan 24 '19 at 19:52
13

If you are writing your own model, just include the Qt.ItemIsUserCheckable flag in the return value from the flags() method, and ensure that you return a valid value for the Qt.CheckStateRole from the data() method.

If you use the QStandardItemModel class, include the Qt.ItemIsUserCheckable flag in those you pass to each item's setFlags() method, and set the check state for the Qt.CheckStateRole with its setData() method.

In an interactive Python session, type the following:

from PyQt4.QtGui import *

model = QStandardItemModel()
item = QStandardItem("Item")
item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
item.setData(QVariant(Qt.Checked), Qt.CheckStateRole)
model.appendRow(item)

view = QListView()
view.setModel(model)
view.show()
Omar Einea
  • 2,478
  • 7
  • 23
  • 35
David Boddie
  • 1,016
  • 7
  • 4