Hrvoje T
Hrvoje T

Reputation: 3923

Which one is a parent of child class ChildWidget (PySide)?

Can you help me and explain why print(str(self.parent())) returns MainWindow and self.print_base() returns QWidget? Where is parent() method defined? In super(ChildWidget, self).__init__(parent) parent goes to MainWindow init or in QWidget init?

import sys
from PySide import QtGui, QtCore

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.do_something() #sanity check
        self.cw = ChildWidget(self)
        self.setCentralWidget(self.cw)
        self.show()

    def do_something(self):

        print 'doing something!'

class ChildWidget(QtGui.QWidget):
    def print_base(self):
        for base in self.__class__.__bases__:
            print base.__name__

    def __init__(self, parent):
        super(ChildWidget, self).__init__(parent)

        print(str(self.parent()))
        self.print_base()

        self.button1 = QtGui.QPushButton()
        self.button1.clicked.connect(self.do_something_else)

        self.button2 = QtGui.QPushButton()
        self.button2.clicked.connect(self.parent().do_something)

        self.layout = QtGui.QVBoxLayout()
        self.layout.addWidget(self.button1)
        self.layout.addWidget(self.button2)
        self.setLayout(self.layout)
        self.show()

    def do_something_else(self):
        print 'doing something else!'

Upvotes: 1

Views: 68

Answers (1)

Carlos H Romano
Carlos H Romano

Reputation: 626

You are dealing with two types of hierarchy: 1) widgets hierary; 2) python classes hiearchy. The method "print_base" is listing all the base classes in a python POV, while "parent" returns the widget instance where the child widget is attached to.

Upvotes: 1

Related Questions