我有以下代码无法捕获关键事件。 我使用uic.loadUi()来加载我的GUI。 但我似乎无法抓住键盘事件。
请帮助!
class cMyApp(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self)
self.ui = uic.loadUi("myApp.ui")
#~ self.ui.show() # Show myApp UI but key event Doesn't Work :(
self.show() # Show a small window but key event works.
def keyPressEvent(self, event):
if type(event)==QtGui.QKeyEvent:
print ("type(event) = ",type(event))
if event.key()==QtCore.Qt.Key_Escape:
print("Esc pressed!!!")
self.close()
event.accept()
else:
event.ignore()
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
myApp = cMyApp()
sys.exit(app.exec_())
答案 0 :(得分:2)
使用uic.loadUI()加载时,必须提供'self'作为baseinstance的另一个参数;否则默认为无。
更正后的代码部分应为:
self.ui = uic.loadUi("myApp.ui", self) # Must supply 'self' as baseinstance.
self.ui.show() # Show myApp UI can work with key event now! :)