【发布时间】: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。我对这个网站和编程很陌生,对于任何错误,我深表歉意。提前致谢!
【问题讨论】: