我知道这个问题很简单,但我还是被困住了。 有没有任何方法可以从继承的小部件类中获取父布局小部件名称?
我这里有一小段代码。所以基本上我需要在现在打印“按下按钮”的标签字段中打印 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。我对这个网站和编程都很陌生,对于任何错误,我深表歉意。提前致谢!
最佳答案
变量的名称本身是不可能获得的,因为变量的名称是相对的,例如,如果代码如下:
# ...
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())
关于python - 如何从子窗口小部件类中打印父窗口小部件的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55955122/