Can't change state of checkable QListViewItem with custom widget

☆樱花仙子☆ 提交于 2019-12-05 13:06:43

I'm not sure why exactly list item doesn't want to change its state when widget is set. I guess the workaround for this issue would be either adding a check box in your widget or connect to the listwidget's itemClicked signal and reset item's state there. Pls, see if an example below would work for you:

import sys
from PyQt4 import QtGui, QtCore

class MainForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainForm, self).__init__(parent)

        listWidget = QtGui.QListWidget()

        item = QtGui.QListWidgetItem()
        item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
        item.setCheckState(QtCore.Qt.Unchecked)
        listWidget.addItem(item)

        widget = QtGui.QCheckBox('test')
        item.setSizeHint(widget.sizeHint())
        listWidget.setItemWidget(item, widget)

        listWidget.itemClicked.connect(self.on_listWidget_itemClicked)

        self.setCentralWidget(listWidget)

    def on_listWidget_itemClicked(self, item):
        if item.listWidget().itemWidget(item) != None: 
            if item.checkState() == QtCore.Qt.Checked:
                item.setCheckState(QtCore.Qt.Unchecked)
            else:
                item.setCheckState(QtCore.Qt.Checked)

def main():
    app = QtGui.QApplication(sys.argv)
    form = MainForm()
    form.show()
    app.exec_()

if __name__ == '__main__':
    main()

hope this helps, regards

rohanpm

The docs for QListWidget::setItemWidget say:

This function should only be used to display static content in the place of a list widget item. If you want to display custom dynamic content or implement a custom editor widget, use QListView and subclass QItemDelegate instead.

By "static content" I suppose it means non-interactive, indicating that this is a known limitation when using QListWidget.

STiAT

It is absolutely the same in C++, so not only a python / pyqt problem (played around with that for some time now to see if I can find a solution). I first thought this is the old bug with Qt::ItemIsEnabled coming back which we already had in 4.2, but it was not.

This is either working as intended and not enough described in the documentation (my +1 for this), or a bug.

To be sure about this, I would file a bug at https://bugreports.qt.io, and see what they say about this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!