Search code examples
pythonpyqtqlistwidget

Is it possible to have a QListWidget select multiple setCurrentItems


In PyQt I can have QListWidget select an item programmatically using QListWidget.setCurrentItem(item). And this, of course, will select an item for me inside my QListWidget.

However, I'm wondering if there exists a method like setCurrentItems([item1, item2, item3]) where if I give a list, it will select all the items in QListWidget that match those items.

Right now my current implementation only allows me to select one item. In this case, the item 'data2'

index = ['data', 'data1', 'data2']
for i in index:
    matching_items = listWidget.findItems(i, QtCore.Qt.MatchExactly)
    for item in matching_items:
        listWidget.setCurrentItem(item)

enter image description here

It would be cool if something like this could be done.

index = ['data', 'data1', 'data2']
for i in index:
    matching_items.append(listWidget.findItems(i, QtCore.Qt.MatchExactly))
listWidget.setCurrentItems(matching_items)

enter image description here


Solution

  • QListWidget by default supports a single selection, you must change the selection mode with setSelectionMode, in your case:

    listWidget.setSelectionMode(QListWidget.MultiSelection)
    

    If you want a QListWidgetItem to be selected you must use setSelected(True).

    Example:

    if __name__ == '__main__':
        app = QApplication(sys.argv)
        listWidget = QListWidget()
    
        listWidget.addItems(["data{}".format(i) for i in range(10)])
    
        listWidget.setSelectionMode(QListWidget.MultiSelection)
        index = ['data2', 'data3', 'data5']
        for i in index:
            matching_items = listWidget.findItems(i, Qt.MatchExactly)
            for item in matching_items:
                item.setSelected(True)
    
        listWidget.show()
        sys.exit(app.exec_())
    

    enter image description here