如何从另一个 class 调用 QMainWindow 组件?

How to call QMainWindow components from another class?

我需要从另一个 class 调用一个 QMainWindow 的对象,但我找不到使其工作的方法。这是问题的最小示例:

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_())

Window正常打开,调用Starter class,打印“starter”,也调用show_label,打印“show”,但没有出现标签在 window。这种方法有什么问题?

首先,我建议您对 classes and instances 是什么以及它们的工作原理进行一些研究。

那么另一个不可忽视的重要方面是垃圾收集,这就是Python如何确保在不再需要对象时不会浪费内存.
对于您在 Starter 中创建的 MainWindow 实例,以及代码末尾的 Starter() 本身,都会发生这种情况。

最后,在您的 Starter class 中,您没有使用您正在考虑的 MainWindow 实例(在脚本末尾创建的实例),而是另一个实例,在 Starter 的 __init__() 之外绝对没有任何引用:一旦执行该行,instance 就会被删除。

考虑到以上几个方面,尝试以下修改,了解其中的区别。

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_())