0

By pressing a QPushButton in my QDialog window I want to open a new QWidget window. My code:

from PyQt4 import QtGui
import sys


class MainWindow(QtGui.QWidget):

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.setWindowTitle("Main Window")


class FirstWindow(QtGui.QDialog):

    def __init__(self, parent=None):
        super(FirstWindow, self).__init__(parent)

        self.createWindow()

    def createWindow(self):
        btn = QtGui.QPushButton('Open New Window', self)
        btn.move(10, 10)

        self.openNewWindow = MainWindow(self)
        btn.clicked.connect(self.openMainWin)

        self.setGeometry(250,250, 150,50)
        self.setWindowTitle("First Window")
        self.show()

    def openMainWin(self):
        self.openNewWindow.show()


if __name__ == "__main__":

    app = QtGui.QApplication(sys.argv)
    firstwin = FirstWindow()
    sys.exit(app.exec_())

When I run the code nothing happens by pressing the button.

But when I change the class from class MainWindow(QtGui.QWidget) to class MainWindow(QtGui.QDialog) or class MainWindow(QtGui.QMainWindow) it works!

What am I doing wrong?! Please assist me.

Timo
  • 138
  • 2
  • 11

1 Answers1

2

When you instantiate MainWindow you pass in a parent. Qwidget only makes a new window if you don't specify a parent.

This is of course deliberate. If QWidgets with parents were shown in new windows, then you could never build a GUI. Imagine having every widget in it's own window!

QMainWindow and QDialog are specifically designed to both have a parent, and create a new window. You should use them.

three_pineapples
  • 11,579
  • 5
  • 38
  • 75