Search code examples
pythonpyqtpyqt4qt-designer

How to open a new window from the main one


I have created two windows with Qt designer. Now in a third file, I'm trying to import the classes and open one of them by clicking a QPushButton in the other one.

The first one, main_gui.py, is something like this:

from PyQt4 import QtCore, QtGui    
try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s    
try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName(_fromUtf8("Form"))
...
...
...
if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    Form = QtGui.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

The second one, single_plot_gui.py, has the same preamble and it looks like this:

class Ui_Form_single_plot(object):
    def setupUi(self, Form_single_plot):
        Form_single_plot.setObjectName(_fromUtf8("Form_single_plot"))
...
...
...
if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    Form_single_plot = QtGui.QWidget()
    ui = Ui_Form_single_plot()
    ui.setupUi(Form_single_plot)
    Form_single_plot.show()
    sys.exit(app.exec_())

Now in my third file I have:

from main_gui import Ui_Form
from single_plot_gui import Ui_Form_single_plot

class SinglePlotWindow(QtGui.QMainWindow, Ui_Form_single_plot):
    def __init__(self, parent=None):
        super(SinglePlotWindow, self).__init__(parent)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.setupUi(self)

class Main_Window(QtGui.QWidget, Ui_Form):
    def __init__(self, parent=None):
        super(Main_Window, self).__init__(parent)
        self.setupUi(self)
        self.open_single_plotButton.clicked.connect(self.OpenSinglePlot)

    def OpenSinglePlot(self):
        window = SinglePlotWindow(self)
        window.show()

But when I press the open_single_plotButton, the SinglePlotWindow appears on top of the main window, instead of showing a new window. What am I doing wrong?

In this answer they do something very similar, but I'm not getting there...


Solution

  • You need to create the second window without a parent, and keep a reference to it after it's shown. So your button handler should look like this:

        def OpenSinglePlot(self):
            self.plotWindow = SinglePlotWindow()
            self.plotWindow.show()