簡體   English   中英

在主 class 的子類中創建的 PyQt5 小部件的設置屬性

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

我做了一個程序,想用類重寫它。 我不知道如何更改在其外部子類中創建的Qlabel的文本。 這里的代碼:

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

謝謝

所以結果沒問題,但現在我無法從我的其他子類訪問(示例代碼中未顯示)我嘗試這樣:

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

我得到: AttributeError: 'builtin_function_or_method' object 沒有屬性 'myObject'

不需要傳遞父級,使用 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