0
class testWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        super(testWidget, self).__init__(parent)
        self.parent = parent
        self.something()
    def something(self):
        self.parent.callme() # self.parent?.... nice?


class testClass():
    def __init__(self):
        self.widget = testWidget(parent=self)

test = testClass()

What is the cleanest way of dealing with a parent class in python(pyqt)? Is there a nicer way than calling self.parent directly?

1
  • Frankly, calling a parent widget method from its child widget is a bad idea. Either put the method out as a common function, or use event filter to catch focusInEvent event on any widget. Commented Aug 8, 2012 at 11:52

1 Answer 1

1

If you want to call a method of this widget's parent (if one has been set), use QObject.parent():

class TestWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        super(TestWidget, self).__init__(parent)
    def something(self):
        self.parent().callMe()

class TestClass(QtCore.QObject):
    def __init__(self):
        super(TestClass, self).__init__(None)
        self.widget = TestWidget(parent=self)
        ...
    def callMe(self): pass

test = TestClass()
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks guys! parent() was what I was looking for. I'm getting error on focusInEvent() for the widget though, will update the code above
@user1584472, it might be that the widget was reparented, if you've used layouts. I guess this is not a real code, just a simulation?
Yes loadui etc. Yep just quickly showing where it goes boom. I'm not editing the layout after the init point myself
self.parent().hello() # gives error in focusInEvent - print self.parent() at this point to understand what is it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.