python - How PyQt5 keyPressEvent works -
i create ui pyqt gpl v5.4 , use pyuic5 convert *.ui file *.py
but not know how keypressevent work in code!!
it should work qwidget, how let works.
please help!
from pyqt5 import qtcore, qtgui, qtwidgets pyqt5.qtcore import qt pyqt5.qtwidgets import qwidget class ui_mainwindow(qwidget,object): def setupui(self, mainwindow): mainwindow.setobjectname("mainwindow") mainwindow.resize(200, 200) self.centralwidget = qtwidgets.qwidget(mainwindow) self.centralwidget.setobjectname("centralwidget") self.pushbutton = qtwidgets.qpushbutton(self.centralwidget) self.pushbutton.setgeometry(qtcore.qrect(50, 110, 75, 23)) self.pushbutton.setobjectname("pushbutton") self.retranslateui(mainwindow) qtcore.qmetaobject.connectslotsbyname(mainwindow) def retranslateui(self, mainwindow): _translate = qtcore.qcoreapplication.translate mainwindow.setwindowtitle(_translate("mainwindow", "mainwindow")) self.pushbutton.settext(_translate("mainwindow", "pushbutton"))\ def keypressevent(self, e): if e.key() == qt.key_f5: self.close() if __name__ == "__main__": import sys app = qtwidgets.qapplication(sys.argv) mainwindow = qtwidgets.qwidget() ui = ui_mainwindow() ui.setupui(mainwindow) mainwindow.show() sys.exit(app.exec_())
a recommendation before starting answer, not modify class generates qt designer, in case name think used template mainwindow, in following code added bit of code have removed, must create new class implements generated view:
view:
class ui_mainwindow(object): def setupui(self, mainwindow): mainwindow.setobjectname("mainwindow") mainwindow.resize(200, 200) self.centralwidget = qtwidgets.qwidget(mainwindow) self.centralwidget.setobjectname("centralwidget") self.setcentralwidget(self.centralwidget) self.pushbutton = qtwidgets.qpushbutton(self.centralwidget) self.pushbutton.setgeometry(qtcore.qrect(50, 110, 75, 23)) self.pushbutton.setobjectname("pushbutton") self.retranslateui(mainwindow) qtcore.qmetaobject.connectslotsbyname(mainwindow) def retranslateui(self, mainwindow): _translate = qtcore.qcoreapplication.translate mainwindow.setwindowtitle(_translate("mainwindow", "mainwindow")) self.pushbutton.settext(_translate("mainwindow", "pushbutton"))
the class implements view must inherit class of template, in case of qmainwindow, , use setupui method in addition calling parent constructor, ie in case of qmainwindow.
logic:
class mainwindow(qmainwindow, ui_mainwindow): def __init__(self, parent=none): qmainwindow.__init__(self, parent=parent) self.setupui(self) def keypressevent(self, e): if e.key() == qt.key_f5: self.close() if __name__ == "__main__": import sys app = qtwidgets.qapplication(sys.argv) w = mainwindow() w.show() sys.exit(app.exec_())
with modifications keypressevent method works.
Comments
Post a Comment