Move cursor focus from one QLabel to another QLabel in Pyqt5?

Question:

I have 7 Qlabels placed in Qgridlayout with 2 rows and 4 columns. I need to change focus from one to another by arrow keys pressing( right, down, left, up). How to get it in pyqt5?

Asked By: Bala

||

Answers:

You can enable keyboard focus policy on the labels using label.setFocusPolicy(Qt.TabFocus). Then you would need to register an event filter on each of the labels. And then create an event filter method that listens for arrow key events and changes the focus.

For example:

class Window(QWidget):
    def __init__(self, parent=None) -> None:
        super().__init__(parent=parent)
        self.layout = QGridLayout(self)
        self.labels = []
        for i in range(2):
            for j in range(4):  # create grid of labels
                label = QLabel(f"Label -> ({i},{j})", self)
                self.layout.addWidget(label,i,j,1,1)
                self.labels.append(label)
                label.installEventFilter(self)   # add event filter
                label.setFocusPolicy(Qt.TabFocus) # set focus policy
        # set the focused widgits background color
        self.setStyleSheet("QLabel:focus {background-color: #0f9;}")

    def eventFilter(self, source, event):
        typ, arrows = event.type(), [Qt.Key_Left, Qt.Key_Right, Qt.Key_Down, Qt.Key_Up]
        # verify the type of event and which key was pressed
        if typ == QEvent.KeyPress and event.key() in arrows:
            key = event.key()
                if key in arrows[:2]:
                    self.focusNextPrevChild(event.key() == arrows[1])
                else:
                    inc = -1 if key == arrows[-1] else 1
                    current = self.focusWidget()
                    pos = self.grid.getItemPosition(self.grid.indexOf(current))
                    widget = self.grid.itemAtPosition(pos[0] + inc,pos[1])
                    widget.widget().setFocus()
                return True
        return super().eventFilter(source, event)

I only included left and right in the example… But this should be more than enough to give you the general idea

Answered By: Alexander
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.