0
votes

I have a QListWidget with few elements. Moving through the list is done with the arrow keys. How to make the "infinite loop", meaning that whan the last item is reached and you go down, the selection jumps to the first item, and reverse from first to last if you want to go up? Here is part of the code for creating list widget:

    self.listWidget = QtGui.QListWidget(Form)
    self.listWidget.setFont(font)
    self.listWidget.setFocusPolicy(QtCore.Qt.StrongFocus)
    self.listWidget.setAutoFillBackground(True)
    self.listWidget.setAlternatingRowColors(True)
    self.listWidget.setWordWrap(True)
    self.listWidget.setSelectionRectVisible(True)
    self.listWidget.setObjectName("listWidget")
    self.listWidget.hasFocus()
    self.listWidget.itemActivated.connect(self.klik)
    self.gridLayout.addWidget(self.listWidget, 0, 0, 1, 1)
1

1 Answers

1
votes

In order to do such a circular list, you can subclass QListWidget, override its keyPressEvent() method and check whether you are in the first/last row before moving via setCurrentRow() if needed.

class CircularListWidget(QtGui.QListWidget):
    """
    Circular ListWidget.
    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Down:
            if self.currentRow() == self.count()-1:
                self.setCurrentRow(0)
                return
        elif event.key() == QtCore.Qt.Key_Up:
            if self.currentRow() == 0:
                self.setCurrentRow(self.count()-1)
                return

        # Otherwise, parent behavior
        super().keyPressEvent(event)

Just replace your QListWidget by this CircularListWidget and it should work. I did not find any built-in method to do what you ask for, hence this workaround.