How PyQt5 keyPressEvent works

后端 未结 1 887
终归单人心
终归单人心 2021-01-13 17:43

I create a UI from PyQt GPL v5.4 and use pyuic5 convert *.ui file to *.py

But I do not know how keyPressEvent work in this code!!

It should work for QWidget,

相关标签:
1条回答
  • 2021-01-13 18:27

    A recommendation before starting my answer, do not modify the class that generates Qt Designer, in your case by the name I think you used the template MainWindow, in the following code I added a bit of code that you have removed, what you must do is Create a new class that implements the 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 that implements the view must inherit from the class of the template, in your case of QMainWindow, and use the setupUI method in addition to calling the parent constructor, ie in your 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 those modifications the keyPressEvent method already works.

    0 讨论(0)
提交回复
热议问题