Issue
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?
Solution
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.layout.getItemPosition(self.layout.indexOf(current))
widget = self.layout.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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.