【问题标题】:How to call QMainWindow components from another class?如何从另一个类调用 QMainWindow 组件?
【发布时间】:2021-02-07 22:24:12
【问题描述】:

我需要从另一个类中调用 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_())

窗口正确打开并调用Starter class,打印“starter”,还调用show_label,打印“show”,但标签没有出现在窗口中。这种方法有什么问题?

【问题讨论】:

    标签: python class pyqt5 qmainwindow


    【解决方案1】:

    首先,我建议你对classes and instances是什么以及它们是如何工作的。

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

    最后,在您的 Starter 类中,您没有使用您正在考虑的 MainWindow 实例(在脚本末尾创建的实例),而是另一个在 @ 之外绝对没有任何参考的实例Starter 的 987654325@:一旦执行该行,该 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_())
    

    【讨论】:

      猜你喜欢
      • 2019-06-24
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-12
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      相关资源
      最近更新 更多