简体   繁体   English

在主 class 的子类中创建的 PyQt5 小部件的设置属性

[英]Setting attribute of a PyQt5 widget created in a subclass within the main class

I made a program and want to rewrite it with classes.我做了一个程序,想用类重写它。 I don't know how to change the text of a Qlabel created in a subclass outside of it.我不知道如何更改在其外部子类中创建的Qlabel的文本。 Here the code:这里的代码:

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel

class MainWindow(QWidget):

    def __init__(self):
        super(MainWindow, self).__init__()
        self.setMinimumSize(300,200)
        self.layout  = QVBoxLayout()
        self.layout.addWidget(MyClass(self))
        self.setLayout(self.layout)
        # i want to change the text label from here
        # with label.setText()

class MyClass(QWidget):

    def __init__(self, parent):
        super(MyClass, self).__init__()
        self.parent = parent
        self.label = QLabel("My text",self)
        self.label.setStyleSheet("color: black;")
        self.label.setGeometry(5, 0, 65, 15) 

if __name__ == "__main__":
    app = QApplication(sys.argv)
    root = MainWindow()
    root.show()
    sys.exit(app.exec_())

Thank you谢谢

So the result is ok but now i canot access from my other subclass (not shown in the sample code) I try like this:所以结果没问题,但现在我无法从我的其他子类访问(示例代码中未显示)我尝试这样:

self.parent.myObject.label.setText("new text")

I get: AttributeError: 'builtin_function_or_method' object has no attribute 'myObject'我得到: AttributeError: 'builtin_function_or_method' object 没有属性 'myObject'

It is not necessary to pass the parent, just use the object reference:不需要传递父级,使用 object 参考即可:

class MainWindow(QWidget):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setMinimumSize(300,200)
        self.layout  = QVBoxLayout()
        self.myclass = MyClass()
        self.layout.addWidget(self.myclass)
        self.setLayout(self.layout)
        # i want to change the text label from here
        self.myclass.label.setText("Foo")

class MyClass(QWidget):
    def __init__(self, parent=None):
        super(MyClass, self).__init__(parent)
        self.label = QLabel("My text",self)
        self.label.setStyleSheet("color: black;")
        self.label.setGeometry(5, 0, 65, 15) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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