Search code examples
pythonqtchildwindowqmainwindow

Value in MainWindow returned from childWindow


How do I send a value from a ChildWindow to a MainWindow once the ChildWindow is closed?.

When the "closeButton" in ChildWindow is pressed, ChildWindow sends the calculated value to MainWindow.

I did a test like this:

def closeEvent(self, evnt):
        value = 34
        return value

And it didn't work, I got this:

TypeError: invalid result type from ChildWindow.closeEvent()

Solution

  • Here is simple example how you can do that:

    import sys
    from PyQt4 import QtGui
    
    
    class Window(QtGui.QWidget):
        def __init__(self):
            QtGui.QWidget.__init__(self)
    
            self.button = QtGui.QPushButton("Make child")
            self.button.clicked.connect(self.openChildWindow)
    
            layout = QtGui.QVBoxLayout(self)
            layout.addWidget(self.button)
    
        def openChildWindow(self):
            self.childWindow = ChildWindow(self)
            self.childWindow.setGeometry(650, 350, 200, 300)
            self.childWindow.show()
    
        def printResult(self, value):  
            print value
    
    class ChildWindow(Window):
        def __init__(self, parentWindow):
            super(ChildWindow, self).__init__()
            self.parentWindow = parentWindow
            self.parentWindow.printResult("I'm in child init")
            self.button.setDisabled(1)
    
        def closeEvent(self, event):
            self.parentWindow.printResult("Closing child, this text is returned to parent")
    
    if __name__ == '__main__':
    
        app = QtGui.QApplication(sys.argv)
        window = Window()
        window.setGeometry(600, 300, 200, 300)
        window.show()
        sys.exit(app.exec_())