Parent () or super () to get parent object?

I have two classes:

The first (parent class) creates an instance of the child class in the method. I am trying to change the properties of parent objects inside a child class. (These objects are PyQT QWidget

s).

Here is the start of my parent and child classes:

Parent:

class ParentClass(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(ParentClass, self).__init__()

        somevar=1200

        self.ChildItem=ChildClass()
        self.ChildItem.Start(somevar)

      

Child:

class ChildClass(QtGui.QWidget):
    def Start(self, var):
        super(ChildClass, self).__init__(self)

        self.parent().resize(var,var)

      

However, even if I have no errors, the last line produces nothing.

I've seen in a couple of examples what super()

can be used to call parent methods, so I guess this would be the solution for my case. However, I was unable to get it to work.

I have a lot of problems realizing super()

it always gets caught up in complex concepts like multiple inheritance when I just want to do a simple thing.

+3


source to share


2 answers


The problem here has nothing to do with super

or inheritance. With inheritance, parent-child relationships are between classes. But in your example ChildClass

does not inherit ParentClass

, so it doesn't matter.

There is another type of parent / child relationship in Qt in Qt and this happens between instances. Constructors for widgets have an argument that allows you to pass a reference to the parent object (usually another instance of the widget). However, the argument is optional, so unless you explicitly set it, the call parent()

after that will just return None

.

The specific error in your code example is that the child is never given a parent.



This is what your example looks like:

class ParentClass(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(ParentClass, self).__init__()    
        # pass in "self" as the parent
        self.ChildItem = ChildClass(self)
        self.ChildItem.Start(1200)

class ChildClass(QtGui.QWidget):
    def Start(self, var):
        self.parent().resize(var, var)

      

+1


source


A parent in Qt terminology is not a parent in python terminology, from the docs :

Returns a pointer to the parent object.

QObjects are organized in object trees. When you create a QObject with another object as a parent, the object will automatically add itself to the parent's children () list.

But the parent here in Qt terminology, the object that this object belongs to has nothing to do with python inheritance.



For python inheritance, you need super

:

super(ParentClass, self).method()

      

This is trivial in the case of single inheritance.

+2


source







All Articles