【问题标题】:Setting attribute of a PyQt5 widget created in a subclass within the main class设置在主类的子类中创建的 PyQt5 小部件的属性
【发布时间】:2021-12-07 17:40:01
【问题描述】:

我做了一个程序,想用类重写它。 我不知道如何更改在它的子类 outside 中创建的 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_())

谢谢

【问题讨论】:

  • 你的问题不清楚。您在哪里尝试更改在其外部子类中创建的Qlabel 的文本?发生了什么,有错误信息吗?

标签: python pyqt5


【解决方案1】:

不需要传递父级,使用对象引用即可:

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) 

【讨论】:

  • 谢谢你,我已经找到了解决方案,但我发布时出错了。将 parent=none 放在声明中重要吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-27
  • 1970-01-01
  • 2011-06-16
  • 1970-01-01
  • 2019-06-23
  • 2017-08-03
  • 1970-01-01
相关资源
最近更新 更多