我正在尝试使用以下代码获取keypressevent工作
import sys,
from PyQt4 import QtCore, QtGui
class Ui_MainWindow(QtGui.QWidget):
def __init__(self):
super(Ui_MainWindow, self).__init__()
def keyPressEvent(self, event):
print 'a'
def setupUi(self, MainWindow):
MainWindow.setObjectName(("MainWindow"))
MainWindow.resize(371, 345)
MainWindow.setMaximumSize(QtCore.QSize(401, 600))
MainWindow.setWindowIcon(QtGui.QIcon('icons/icon.png'))
screen = QtGui.QDesktopWidget().screenGeometry()
mysize = MainWindow.geometry()
hpos = ( screen.width() - mysize.width() ) / 2
vpos = ( screen.height() - mysize.height() ) / 2
MainWindow.move(hpos, vpos)
#some GUI
MainWindow.setCentralWidget(self.centralwidget)
cd=MainWindow.centralWidget()
cd.setFocusPolicy(QtCore.Qt.StrongFocus)
cd.setFocus()
self.actionHardware = QtGui.QAction(MainWindow)
self.actionHardware.setObjectName(("actionHardware"))
self.retranslateUi(MainWindow)
#COnnect odes
def retranslateUi(self, MainWindow):
#sime button text codes
if __name__=="__main__" :
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
使用QTDesigner部分生成代码。我注意到用ui.show()替换Mainwindow.show()会启用keypressevent,但代价是不显示我在Mainwindow中心窗口小部件中创建的任何按钮
答案 0 :(得分:1)
看起来问题在于您重新使用Designer的代码输出。您定义了Ui_MainWindow.keyPressEvent,并创建了该类的实例“ui”。但是:“ui”永远不会直接合并到GUI中(ui.setupUi会向MainWindow添加其他小部件,但不会自己添加),因此事件永远不会传递给ui。
我的方法看起来更像是这样:
class Ui_MainWindow(object): ## note this does not need to inherit QWidget
... ## and ideally, this code should not be changed
... ## after designer generates it
...
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
def keyPressEvent(self, ev):
print "key press"
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
MainWindow = Window()
MainWindow.show()
sys.exit(app.exec_())