当用户与列表交互时,如何获取 QListWidget 的所有选定项目? [英] How can I get all selected items for a QListWidget when the user interacts with the list?

查看:52
本文介绍了当用户与列表交互时,如何获取 QListWidget 的所有选定项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在用户与列表交互时激活的事件处理程序(插槽")中获取 QListWidget 的所有选定项目?换句话说,当用户执行一个操作(比如在列表中选择一个新选项)时,我需要有可用的所选项目的完整列表

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)

到目前为止我尝试过的是使用 QListWidget.currentItemChanged 然后尝试使用 QListWidget.selectedItems() 获取所有选定的列表项我的问题使用这种方法是从 selectedItems() 函数返回的列表直到退出我连接到 currentItemChanged

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

我正在寻找的解决方案必须使用MultiSelection"(可以同时选择多个列表项)

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

推荐答案

您必须使用 itemSelectionChanged 信号,该信号在选择任何项目时激活.

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_())

输出:

start
['2']
start
['2', '3']
start
['2', '3', '4']
start
['2', '3', '4', '6']

这篇关于当用户与列表交互时,如何获取 QListWidget 的所有选定项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆