I have two widgets in my application, and I want to do something in the widget when the key is pressed. However, I find only one widget response the key press event even the other one has the focus.
The code to reproduce my problem is:
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys, os
class Widget(QLabel):
def __init__(self, name=''):
super().__init__(name)
self.setFocusPolicy(Qt.ClickFocus)
self.grabKeyboard()
self.name=name
def keyPressEvent(self, *args, **kwargs):
super().keyPressEvent(*args, **kwargs)
print('key press: ', self.name)
def focusInEvent(self, *args, **kwargs):
super().focusInEvent(*args, **kwargs)
print('focus in: ', self.name)
class MyWin(QFrame):
def __init__(self):
super().__init__()
self.resize(100, 100)
layout = QHBoxLayout()
self.setLayout(layout)
self.w1 = Widget('w1')
self.w1.setStyleSheet('background-color: rgb(255, 0, 0)')
layout.addWidget(self.w1)
self.w2 = Widget('w2')
self.w2.setStyleSheet('background-color: rgb(0, 255, 0)')
layout.addWidget(self.w2)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MyWin()
window.show()
app.exec_()
When I press the key board, only w2
response the key press event. How to let both two widgets response the key press event?
Enviornment is:
win10
python 3.7
pyqt 5.15.4
Don't use widget.grabKeyboard() as this will force all keyboard input to be re-directed to the last widget which called the method.