How to call the method in the parent widget in the child widget in PyQt

In PyQt, for the convenience of hierarchical management, most of the time there is a distinction between child widgets and parent widgets. For example, the parent widget is a QWidget, the child widget is a QTabWidget, the child widget is located in the parent widget, and the child widget is a widget of the parent widget. .

Obtaining child parts from the parent part is very simple, needless to say. When creating a child part in the parent part, you can use a variable to bind the child part.

However, it seems that there is no clear way to get the parent part from the child part. The solution found on the Internet is either that the final result is ambiguous and ambiguous, or simply does not apply to the python language.

After several simple experiments, I found that the solution is relatively simple, so here is a simple record.

When the parent part is initialized, self is passed to the child part as the parent part when defining the child part, which is roughly like this:

#self指的是父部件,Interface是子部件的实例化类
#定义一个Interface,即可创建一个子部件并对之进行初始化
self.tab=childWidget.Interface(self)

Then, in the child component, when initializing, define a parent variable, receive the self parameter passed from the parent component, and assign it to the parent variable. The code is probably as follows:

#self指的是新建的子部件
#parent是父部件传过来的参数
def __init__(self,parent):
    super(Interface,self).__init__()
    self.parent=parent

In this case, in the child part, as long as you use self.parent, you can get the parent part, and then you can call the properties, methods and other child parts in the parent part.

Guess you like

Origin blog.csdn.net/esa72ya/article/details/89305924