我不确定为什么以下最小代码打印鼠标但不打印键盘事件。据我所知,这两种方法都在我的自定义小部件中正确重载(位于主窗口内)。有什么想法吗?
from sys import argv, exit
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setCentralWidget(CustomWidget(self))
self.show()
class CustomWidget(QWidget):
def __init__(self, parent=None):
super(CustomWidget, self).__init__(parent)
pass
def mousePressEvent(self, event):
print(event)
def keyPressEvent(self, event):
print(event)
if __name__ == '__main__':
app = QApplication(argv)
ex = MainWindow()
exit(app.exec_())
答案 0 :(得分:0)
经过一番谷歌搜索后,我在Qt docs中找到了这个:
如果小部件处理键盘事件,则必须为小部件启用键盘焦点。这通常是从小部件的构造函数完成的。例如,QLineEdit构造函数调用setFocusPolicy(Qt :: StrongFocus)。
因此,使用行self.setFocusPolicy(Qt.StrongFocus)
添加焦点策略可以解决问题。
完整的更正代码如下:
from sys import argv, exit
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setCentralWidget(CustomWidget(self))
self.show()
class CustomWidget(QWidget):
def __init__(self, parent=None):
super(CustomWidget, self).__init__(parent)
self.setFocusPolicy(Qt.StrongFocus)
pass
def mousePressEvent(self, event):
print(event)
def keyPressEvent(self, event):
print(event)
if __name__ == '__main__':
app = QApplication(argv)
ex = MainWindow()
exit(app.exec_())