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)
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)
QListWidget is a convenience class that provides a list view similar to the one supplied by QListView , but with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list.
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_())
In addition to eyllanesc's answer. You can also opt for:
listWidget.setSelectionMode(QtListWidget.ExtendedSelection)
This will let you hold the Ctrl
key to toggle an item's selection on/off. In addition to that, you can also hold the Shift
key to toggle the selection of all items between the current item and the clicked item.
If you only want the Shift
key selection feature but not the Ctrl
key selection toggle feature, you can use:
listWidget.setSelectionMode(QtListWidget.ExtendedSelection)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With