Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Item in QListWidget cannot be checked even set the flags



  • Hi, I am trying to make items in QListWidget checkable by user.
    I followed the instructions in Qt Flags reference to set the QListWidgetItem's flags as ItemIsUserCheckable and set the check state.
    However, when running the program, I found the checkboxes for items are grey and uncheckable.


    Here is my code:

    # import pyside2 modules
    
    app = QApplication()
    widget = QListWidget()
    for i in range(5):
        item = QListWidgetItem(str(i))
        
        item.setFlags(QtCore.Qt.ItemIsUserCheckable)
        item.setCheckState(QtCore.Qt.Unchecked)
        widget.addItem(item)
    
    # For comparison
    item = QListWidgetItem('6')
    widget.addItem(item)
    checkBox = QtWidgets.QCheckBox("This can be checkable")
    widget.setItemWidget(item,checkBox)
    
    widget.show()
    app.exec_()
    

    The program screen:
    e23b5c25-7f46-4e9d-a520-b043ccf24584-image.png

    The items[0-4] seems to be uncheckable.
    The last one can be checkable because it is a checkbox item.

    But items[0-4] should be checkable according to the reference and this tutorial

    This is what I want: (Items are strings, not checkboxes)
    88e9b906-4525-4bc5-9a21-1c9229a74134-image.png (picture from the above tutorial )


    So what did I miss? How could I solve it?

    Thanks for any help!



  • @Moon-River
    Note that your tutorial showed the line:

    item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
    

    You need something like Python:

    item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
    

    else you overwrite all flags, and lose those like Qt::ItemIsEnabled and Qt::ItemIsEditable, etc.

    https://doc.qt.io/qt-5/qlistwidgetitem.html#details

    By default, items are enabled, selectable, checkable, and can be the source of drag and drop operations



  • @JonB
    Wow! Thanks for your help!
    It works! ^_^


Log in to reply