Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get all selected items for a QListWidget when the user interacts with the list?

How can i get all the selected items for a QListWidget inside an event handler ("slot") which is activated when the user interacts with the list? In other words i need to have the full list of selected items available when the user preforms an action (like choosing a new selection in the list)

What i've tried so far is using QListWidget.currentItemChanged and then trying to get all the selected list items with QListWidget.selectedItems() The problem i'm having with this approach is that the list returned from the selectedItems() function is not updated until after exiting the event handler that i have connected to currentItemChanged

The solution that i'm looking for has to work with "MultiSelection" (multiple list items can be selected at the same time)

Grateful for help and with kind regards, Tord

like image 411
sunyata Avatar asked Feb 06 '23 07:02

sunyata


1 Answers

You must use the itemSelectionChanged signal, this is activated when any item is selected.

import sys

from PyQt5.QtWidgets import QAbstractItemView, QApplication, QListWidget, QListWidgetItem, QVBoxLayout, QWidget


class Widget(QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent=parent)
        self.layout = QVBoxLayout(self)
        self.listWidget = QListWidget(self)
        self.layout.addWidget(self.listWidget)
        self.listWidget.setSelectionMode(QAbstractItemView.MultiSelection)
        self.listWidget.itemSelectionChanged.connect(self.on_change)

        for i in range(10):
            item = QListWidgetItem()
            item.setText(str(i))
            self.listWidget.addItem(item)

    def on_change(self):
        print("start")
        print([item.text() for item in self.listWidget.selectedItems()])


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

enter image description here

Output:

start
['2']
start
['2', '3']
start
['2', '3', '4']
start
['2', '3', '4', '6']
like image 53
eyllanesc Avatar answered Feb 08 '23 16:02

eyllanesc