I have a QListWidget and a QPushButton. Suppose my QListWidget contains as follow:
I am trying to achieve each QPushButton click will return me the name of the individual item in the List. Eg.
Currently I am only able to return all the 5 items in the QListWiget, using this code:
items = [obj.text() for obj in my_list.findItems(
'', QtCore.Qt.MatchContains)
]
I tried using for item in items:...
, whenever I click on the button, it will still return me all the 5 items.
How should I achieve this?
You must create a circular counter that increments each time you click, and use the item()
that returns the desired element, then we use the 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_())
Output:
apple
pear
banana
peach
bear
apple
pear
banana
peach
bear
apple