简体   繁体   中英

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. 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'

It is not necessary to pass the parent, just use the object reference:

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) 

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