Search code examples
pythonpyqtqlistwidgetqlistwidgetitem

Get one item at a time in QListWidget


I have a QListWidget and a QPushButton. Suppose my QListWidget contains as follow:

  • apple
  • pear
  • banana
  • peach
  • bear

I am trying to achieve each QPushButton click will return me the name of the individual item in the List. Eg.

  • First click will return me 'apple',
  • Second click will return me 'pear',
  • ...
  • Fifth click will return me 'bear'
  • And on the sixth click, it will should return me 'apple' again instead of ending the iteration

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?


Solution

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

    enter image description here

    Output:

    apple
    pear
    banana
    peach
    bear
    apple
    pear
    banana
    peach
    bear
    apple