Is it possible to have a QListWidget select multiple setCurrentItems
Asked Answered
M

2

5

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

Maje answered 6/3, 2018 at 21:46 Comment(5)
I think you need an item based approach. I test it tomorrowGodden
do you want to select several items? a currentItem is a selected item, but not every selected item is a currentItem.Eyeshot
Oh! I see! yeah I want all items that are given in a list to be selectedMaje
@Maje what is obj?Eyeshot
My bad, obj was supposed to be listWidgetMaje
E
8

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

Eyeshot answered 6/3, 2018 at 22:57 Comment(0)
D
3

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)
Depersonalize answered 3/4, 2019 at 21:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.