我有一个带有继续按钮的 QDialog 窗口。继续按钮是默认按钮,因为每当我按下回车键时,都会按下继续按钮。我发现了一个奇怪的现象:当我按三下回车键时,继续按钮按了三下。但是,当我第四次按下它时,整个窗口关闭。我在关闭窗口的继续按钮正下方有一个取消按钮,但我没有将取消按钮设为默认按钮或任何东西。
我想覆盖 keyPressEvent
以便每当我在窗口中时,输入按钮将始终连接到继续按钮。
这就是我现在所拥有的:
class ManualBalanceUI(QtGui.QWidget):
keyPressed = QtCore.pyqtSignal()
def __init__(self, cls):
super(QtGui.QWidget, self).__init__()
self.window = QtGui.QDialog(None, QtCore.Qt.WindowSystemMenuHint)
self.ui = uic.loadUi('ManualBalanceUI.ui', self.window)
self.keyPressed.connect(self.on_key)
def keyPressEvent(self, event):
super(ManualBalanceUI, self).keyPressEvent(event)
self.keyPressed.emit(event)
def on_key(self, event):
if event.key() == QtCore.Qt.Key_Enter and self.ui.continueButton.isEnabled():
self.proceed() # this is called whenever the continue button is pressed
elif event.key() == QtCore.Qt.Key_Q:
self.window.close() # a test I implemented to see if pressing 'Q' would close the window
def proceed(self):
...
...
但是,这现在似乎没有任何作用。按“Q”不会关闭窗口,我无法确定“回车”键是否有效。
我事先看了这个问题:PyQt Connect to KeyPressEvent
我还查看了 SourceForge 上的所有文档。任何帮助将不胜感激!
最佳答案
您可以采用两种方法,一种是简单地重新实现keyPressevent而不进行任何花哨的工作。像这样
from PyQt4 import QtCore, QtGui
import sys
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.setGeometry(300, 300, 250, 150)
self.show()
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Q:
print "Killing"
self.deleteLater()
elif event.key() == QtCore.Qt.Key_Enter:
self.proceed()
event.accept()
def proceed(self):
print "Call Enter Key"
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
或者当您尝试使用信号时,如果您缺少正确实现此信号的情况,这里是更新版本。
class Example(QtGui.QWidget):
keyPressed = QtCore.pyqtSignal(QtCore.QEvent)
def __init__(self):
super(Example, self).__init__()
self.setGeometry(300, 300, 250, 150)
self.show()
self.keyPressed.connect(self.on_key)
def keyPressEvent(self, event):
super(Example, self).keyPressEvent(event)
self.keyPressed.emit(event)
def on_key(self, event):
if event.key() == QtCore.Qt.Key_Enter and self.ui.continueButton.isEnabled():
self.proceed() # this is called whenever the continue button is pressed
elif event.key() == QtCore.Qt.Key_Q:
print "Killing"
self.deleteLater() # a test I implemented to see if pressing 'Q' would close the window
def proceed(self):
print "Call Enter Key"
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
关于python - 在 QWidget 中实现 keyPressEvent,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38507011/