您必须创建一个循环计数器,每次单击时都会递增,并使用item()
返回所需元素的 ,然后我们使用text()
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton, QListWidget, QApplication, QListWidgetItem
import sys
class Widget(QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent=parent)
layout = QVBoxLayout(self)
btn = QPushButton("btn", self)
btn.clicked.connect(self.onClicked)
layout.addWidget(btn)
self.listWidget = QListWidget(self)
layout.addWidget(self.listWidget)
elements = ['apple', 'pear', 'banana', 'peach', 'bear']
for element in elements:
self.listWidget.addItem(element)
self.counter = 0
def onClicked(self):
print(self.listWidget.item(self.counter).text())
self.counter = (self.counter +1) % self.listWidget.count()
app = QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
输出:
apple
pear
banana
peach
bear
apple
pear
banana
peach
bear
apple