QListWidget可以选择多个setCurrentItems吗

2024-09-30 22:18:03 发布

您现在位置:Python中文网/ 问答频道 /正文

在PyQt中,我可以让QListWidget使用QListWidget.setCurrentItem(item)以编程方式选择一个项目。当然,这将在我的QListWidget中为我选择一个项目。在

但是,我想知道是否存在类似setCurrentItems([item1, item2, item3])的方法,如果我给出一个列表,它将选择QListWidget中与这些项匹配的所有项。在

现在,我当前的实现只允许我选择一个项目。在本例中,项目“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

如果能做这样的事就好了。在

^{pr2}$

enter image description here


Tags: 项目inforindex编程方式itemsitem
2条回答

除了艾伦斯的回答。您还可以选择:

listWidget.setSelectionMode(QtListWidget.ExtendedSelection)

这将允许您按住Ctrl键来打开/关闭项目的选择。除此之外,您还可以按住Shift键在当前项和单击的项之间切换所有项的选择。在

如果您只需要Shift键选择功能而不是Ctrl键选择切换功能,则可以使用:

listWidget.setSelectionMode(QtListWidget.ExtendedSelection)

QListWidget默认情况下支持单个选择,您必须使用setSelectionMode更改选择模式,在您的情况下:

listWidget.setSelectionMode(QListWidget.MultiSelection)

如果要选择QListWidgetItem,则必须使用setSelected(True)。在

示例:

^{pr2}$

enter image description here

相关问题 更多 >