Arjun Jain
Arjun Jain

Reputation: 409

How to call one mainwindow to another mainwindow in Qt (or PyQt)

In my project i have created two mainwindow i want to call mainwindow2 from the mainwindow1 (which in running). in mainwindow1 i am already used the app.exec_() (PyQt) and to show maindow2 i am using the maindow2.show() in the click event of the button but does not show anything

Upvotes: 0

Views: 6538

Answers (1)

Gary Hughes
Gary Hughes

Reputation: 4510

Calling mainwindow2.show() should work for you. Could you give a more complete example of your code? There may be something wrong somewhere else.

EDIT: Code updated to show an example of how to hide and show windows when opening and closing other windows.

from PyQt4.QtGui import QApplication, QMainWindow, QPushButton, \
            QLabel, QVBoxLayout, QWidget
from PyQt4.QtCore import pyqtSignal

class MainWindow1(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent) 
        button = QPushButton('Test')
        button.clicked.connect(self.newWindow)
        label = QLabel('MainWindow1')

        centralWidget = QWidget()
        vbox = QVBoxLayout(centralWidget)
        vbox.addWidget(label)
        vbox.addWidget(button)
        self.setCentralWidget(centralWidget)

    def newWindow(self):
        self.mainwindow2 = MainWindow2(self)
        self.mainwindow2.closed.connect(self.show)
        self.mainwindow2.show()
        self.hide()

class MainWindow2(QMainWindow):

    # QMainWindow doesn't have a closed signal, so we'll make one.
    closed = pyqtSignal()

    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.parent = parent
        label = QLabel('MainWindow2', self)

    def closeEvent(self, event):
        self.closed.emit()
        event.accept()

def startmain():
    app = QApplication(sys.argv)
    mainwindow1 = MainWindow1()
    mainwindow1.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    import sys
    startmain()

Upvotes: 6

Related Questions