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
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_())
Output:
start
['2']
start
['2', '3']
start
['2', '3', '4']
start
['2', '3', '4', '6']
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