python pyqt and parent class

2019-06-14 02:03发布

问题:

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:

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()