【问题标题】:How to get parent widget's name printed from child widget class?如何从子小部件类中打印父小部件的名称?
【发布时间】:2019-09-21 03:12:10
【问题描述】:

我知道这个问题很简单,但我还是被卡住了。 有什么方法可以从继承的小部件类中获取父布局小部件名称吗?

我这里有一小段代码。所以基本上我需要在现在打印“Push the button”的标签字段中打印self.super_main_layout。

我有一个函数 def print_foo 应该这样做。但我不知道如何从继承的类中获取 parent() 名称。我需要在标签字段中准确地打印出这个self.super_main_layout。

我尝试使用self.parent() 方法,但它不起作用

import sys 
from PyQt5  import QtWidgets, QtCore, QtGui 
from PyQt5.QtWidgets import QApplication

class ButtonTest(QtWidgets.QWidget):
    def __init__(self):
        super(ButtonTest, self).__init__()

        self.setFixedSize(300, 100)
        self.layout = QtWidgets.QHBoxLayout()
        self.setLayout(self.layout)
        self.label = QtWidgets.QLabel("Push the Button")
        self.button = QtWidgets.QPushButton("Button")
        self.button.clicked.connect(self.print_foo)
        self.layout.addWidget(self.label)
        self.layout.addWidget(self.button)

    def print_foo(self):
        ### ???????????
        self.label.setText(str(self.parent().parent())) # ????
        print(self.parent()) # ????

class MyApp(QtWidgets.QWidget):
    def __init__(self):
        super(MyApp, self).__init__()

        self.W = ButtonTest()

        self.setFixedSize(300,300)
        self.super_main_layout = QtWidgets.QVBoxLayout()
        self.setLayout(self.super_main_layout)
        self.super_main_layout.addWidget(self.W)

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

所以现在当您按下按钮时,它会在标签字段中打印无。 但我想要打印布局小部件self.super_main_layout。 有没有办法做到这一点?我现在正在做一个更大的项目。而且我正在编写一个带有按钮的继承类,当按下按钮时我必须在其中获得不同的父名称。 非常感谢。

ps。我对这个网站和编程很陌生,对于任何错误,我深表歉意。提前致谢!

【问题讨论】:

    标签: python pyqt pyqt5


    【解决方案1】:

    变量的名称本身是不可能获得的,因为变量的名称是相对的,例如,如果代码如下:

    # ...
    self.setFixedSize(300,300)
    self.super_main_layout = QtWidgets.QVBoxLayout()
    foo_obj = self.super_main_layout
    self.setLayout(foo_obj)
    self.super_main_layout.addWidget(self.W)
    

    布局的名称是什么:self.super_main_layout 或 foo_obj?因为两个变量都指向同一个对象。

    你可以得到的是对象本身使用父对象,然后是它的布局:

    def print_foo(self):
        pw = self.parentWidget()
        if pw is not None:
            print(pw.layout())
    

    【讨论】:

    • 谢谢!现在我明白了。我会尝试使用你的方法。谢谢
    猜你喜欢
    • 2020-01-01
    • 1970-01-01
    • 2021-05-04
    • 2021-12-30
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多