Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 501
tisaconundrum Avatar asked Mar 06 '18 21:03

tisaconundrum


People also ask

What is QListWidget?

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.


2 Answers

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

like image 81
eyllanesc Avatar answered Sep 18 '22 22:09

eyllanesc


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)
like image 25
Michael Tolentino Avatar answered Sep 18 '22 22:09

Michael Tolentino