我有一个QDialog窗口,有一个继续按钮.继续按钮是默认按钮,因为每当我按下回车键时,按下继续按钮.我发现了一些奇怪的事情:当我按三次回车键时,继续按钮按下三次.但是,当我第四次按它时,整个窗口关闭.我在关闭窗口的继续按钮下方有一个取消按钮,但我没有将取消按钮设为默认按钮或任何东西.
我想覆盖keyPressEvent,这样每当我在窗口时,enter按钮将始终连接到continue按钮.
这就是我现在所拥有的:
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’不关闭窗口,我无法确定’enter’键是否正常工作.
我事先看了这个问题: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()