Aleksandar
Aleksandar

Reputation: 3661

Opening new window from python gui

I have a problem opening new window in my python gui app. I have 3 classes (first login is shown, and than 2 windows are opened). This works fine:

class LoginDialog(QtGui.QDialog):
    def __init__(self, parent = None):
        super(LoginDialog, self).__init__(parent)
    .....

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent = None):
            QtGui.QWidget.__init__(self, parent)
    .....

class ImageViewerMainWindow(QtGui.QMainWindow):
    def __init__(self, path, parent = None):
        super(ImageViewerMainWindow, self).__init__(parent)
    .....

if __name__ == "__main__":
    qtApp = QtGui.QApplication(sys.argv)

    loginDlg = LoginDialog()
    if not loginDlg.exec_():
        sys.exit(-1)

    MyMainWindow = MainWindow()
    MyMainWindow.show()

    viewer = ImageViewerMainWindow("C:\image.jpg")
    viewer.show()

    sys.exit(qtApp.exec_())

I need viewer to be executed from MainWindow but when I put it like this it just flashes and disappear:

class MainWindow(QtGui.QMainWindow):
        def __init__(self, parent = None):
                QtGui.QWidget.__init__(self, parent)
        .....
        def DoOpenImageViewer(self):
                viewer = ImageViewerMainWindow("C:\image.jpg")
                viewer.show()

Upvotes: 0

Views: 1344

Answers (1)

mata
mata

Reputation: 69012

You need to keep a reference to you viewer, otherwise the new window is destroyed when viewer goes out of scope and is garbage collected. If you only need one Window at a time, you can do something like:

class MainWindow(QtGui.QMainWindow):
        def __init__(self, parent = None):
                QtGui.QWidget.__init__(self, parent)
        .....
        def DoOpenImageViewer(self):
                self.viewer = ImageViewerMainWindow("C:\image.jpg")
                self.viewer.show()

Otherwise you could use a list to store the references.

Upvotes: 1

Related Questions