简体   繁体   中英

How to call QMainWindow components from another class?

I need to call objects of a QMainWindow from another class but I can not find a way to make it work. This is a minimal example of the problem:

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel

class Starter:
    def __init__(self):
        super(Starter, self).__init__()
        print("starter")
        MainWindow().show_label()

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setWindowTitle("Start")
        self.show()

    def show_label(self):
        print("show")
        label = QLabel("Hallo")
        self.setCentralWidget(label)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MainWindow()
    Starter()
    sys.exit(app.exec_())

The Window opens properly and the Starter class is called, printing "starter", and also show_label is called, printing "show", but the label doesn't appear in the window. What's wrong with this approach?

First of all, I suggest you to do some research and studying on what classes and instances are and how they work.

Then another important aspect that can't be ignored is garbage collection , which is how Python ensures that no memory is wasted when an object is no more needed.
This happens both for the MainWindow instance you create in Starter, and in the Starter() itself at the end of your code.

Finally, in your Starter class you're not using the MainWindow instance you're thinking (the one created at the end of your script), but another one, which has absolutely no reference whatsoever outside the __init__() of Starter: has soon as that line is executed, that instance gets deleted.

Considering the above aspects, try the following modifications and understand the difference.

class Starter:
    def __init__(self):
        super(Starter, self).__init__()
        self.mainWindow = MainWindow()
        self.mainWindow.show_label()

# ...
if __name__ == '__main__':
    app = QApplication(sys.argv)
    starter = Starter()
    sys.exit(app.exec_())

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