【发布时间】:2018-04-22 08:24:18
【问题描述】:
当用户在 QlistWidget 中选择一个项目然后单击按钮以获取该元素时,我想获取选定的元素
【问题讨论】:
当用户在 QlistWidget 中选择一个项目然后单击按钮以获取该元素时,我想获取选定的元素
【问题讨论】:
试试这个:
from PyQt5.QtWidgets import (QWidget, QListWidget, QVBoxLayout, QApplication)
import sys
class Example(QWidget):
def __init__(self):
super().__init__()
self.l = QListWidget()
for n in range(10):
self.l.addItem(str(n))
self.l.itemSelectionChanged.connect(self.selectionChanged)
vbox = QVBoxLayout()
vbox.addWidget(self.l)
self.setLayout(vbox)
self.setGeometry(300, 300, 300, 300)
self.show()
def selectionChanged(self):
print("Selected items: ", self.l.selectedItems())
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
使用这种方法,您将打印所有通过单击、使用键盘箭头或在其上拖动鼠标来选择的项目。
【讨论】:
您可以使用来自 QListWidget 类的 itemActivated 信号并将其绑定到您的某些方法。
yourQListWidget.itemActivated.connect(itemActivated_event)
def itemActivated_event(item)
print(item.text())
现在每次用户单击 QListWidget 中的某个项目时,都会打印该项目内的文本。
【讨论】:
将方法绑定到来自 QListWidget 的 itemClicked 信号似乎也有效:
yourQListWidget.itemClicked.connect(itemClicked_event)
def itemClicked_event(item):
print(item.text())
对我来说,itemClicked 信号适用于单击项目,而 itemActivated 信号适用于双击。
【讨论】: