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?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
user1584472
  • 1
  • 1
  • 1
  • 2
  • 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](http://stackoverflow.com/questions/9442165/pyqt-mouse-events-for-qtabwidget) to [catch focusInEvent event](http://stackoverflow.com/questions/321656/when-a-qt-widget-gets-focus) on any widget. – warvariuc Aug 08 '12 at 11:52

1 Answers1

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()
warvariuc
  • 57,116
  • 41
  • 173
  • 227
  • 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 Aug 08 '12 at 11:23
  • @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? – warvariuc Aug 08 '12 at 11:33
  • Yes loadui etc. Yep just quickly showing where it goes boom. I'm not editing the layout after the init point myself – user1584472 Aug 08 '12 at 11:35
  • `self.parent().hello() # gives error in focusInEvent` - print `self.parent()` at this point to understand what is it – warvariuc Aug 08 '12 at 11:41