我的应用程序中有两个小部件,我想在按下键时在小部件中做一些事情。但是,我发现只有一个小部件响应按键事件,即使另一个小部件具有焦点。
重现我的问题的代码是:
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_()
当我按下键盘时,只w2
响应按键事件。如何让两个小部件都响应按键事件?
环境是:
win10
python 3.7
pyqt 5.15.4