简体   繁体   中英

What kind of difference does 'self' makes as parameter in PyQt5

In PyQt5, what does self keyword do as a parameter regarding creating Widgets ? I don't see any difference between those two and both work totally fine.

class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        ###############This Part#############
        #QLCDNumber() and QSLider() also works fine below

        lcd = QLCDNumber(self)
        sld = QSlider(Qt.Horizontal, self)

        #####################################

        vbox = QVBoxLayout()
        vbox.addWidget(lcd)
        vbox.addWidget(sld)

        sld.valueChanged.connect(lcd.display)

        self.setLayout(vbox)
        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Signal and slot')
        self.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

There's no difference.

TL;DR;

QWidget inherit from QObject, and QObjects have a tree of hierarchy between parents and children, in C ++ it serves so that when the parent is deleted it eliminates its children so that memory can be handled easily, in the case of PyQt it happens same since the memory handle is not handled directly by python but by C++.

The previous reason is that it serves to pass the parent parameter to the QObjects, on the other hand in the QWidgets the position of the children is always relative to the parent, so if you pass to self as parent the widget will be drawn on the parent.

Going to your specific code there is no difference because the layouts establish the parent of the widgets that handle the widget where it is established so you can eliminate the initial relationship of kinship since the layout will establish it.

We can see the difference if we do not use the layout since when removing the self nobody will establish where the widget will be drawn and therefore the widgets will not be shown.

Without self:

def initUI(self):
    lcd = QLCDNumber()
    sld = QSlider(Qt.Horizontal)

With self:

def initUI(self):
    lcd = QLCDNumber(self)
    sld = QSlider(Qt.Horizontal, self)

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