简体   繁体   中英

Overriding QMainWindow methods in PyQt from QtCreator

I've got this GUI code which is generated by pyuic5 with -x parameter. I have added some of my code to Ui_LEDController such as connecting to arduino through serial port. I want to achieve disconnecting Arduino while program is closed through X .
I know I have to override QMainWindow method closeEvent() , but I wonder what steps should I proceed to achieve this. I can't just create class MyWindow(QtWidgets.QMainWindow()) and then LEDController = MyWindow() , because I will not be able to access serial variable.
So basicly: should I not use this Ui_LEDController to set GUI items and instead of this create class MyWindow(QtWidgets.QMainWindow()) in which I would implement all of the GUI items and override closeEvent() ?

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_LEDController(object):
    def setupUi(self, LEDController):
        LEDController.setObjectName("LEDController")
        LEDController.resize(230, 160)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(LEDController.sizePolicy().hasHeightForWidth())
        LEDController.setSizePolicy(sizePolicy)
        LEDController.setMinimumSize(QtCore.QSize(230, 160))
        LEDController.setMaximumSize(QtCore.QSize(230, 160))
        # Lot of initializing
        LEDController.setCentralWidget(self.central_widget)

        self.retranslateUi(LEDController)
        # Signals and Slots handlers
        QtCore.QMetaObject.connectSlotsByName(LEDController)

    def retranslateUi(self, LEDController):
        _translate = QtCore.QCoreApplication.translate
        LEDController.setWindowTitle(_translate("LEDController", "LEDController"))
        self.bright_label.setText(_translate("LEDController", "Brightness"))
        # Changing text in items


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    LEDController = QtWidgets.QMainWindow()
    ui = Ui_LEDController()
    ui.setupUi(LEDController)
    LEDController.show()
    sys.exit(app.exec_())

You have at least two ways:

subclass both QMainWindow and Ui_LEDController

class MyWindowClass(QMainWindow, Ui_LEDController):

or subclass only QMainWindow with attribute self.ui

class MyWindowClass(QMainWindow):
    def __init__(self):
        ...
        self.ui = Ui_LEDController()
        self.ui.setupUi(self)

and then use all variables of both classes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM