iFunction
iFunction

Reputation: 1268

Show sub window in main window

Can't work out how to embed a window in a main window using classes:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
Qt4 tutorial using classes

This example will be built
on over time.
"""

import sys
from PyQt4 import QtGui, QtCore

class Form(QtGui.QWidget):

    def __init__(self, MainWindow):
        super(Form, self).__init__()


class MainWindow(QtGui.QMainWindow):

    def __init__(self, parent=None):
        super(MainWindow, self).__init__()
        self.setGeometry(50, 50, 1600, 900)
        new_window = Form(self)
        self.show()


def main():
    app = QtGui.QApplication(sys.argv)
    main_window = MainWindow()
    sys.exit(app.exec_())    

if __name__ == "__main__":
    main()

This is supposed to be the single most basic bit of code using classes. How do I get the second window to show please.

Upvotes: 0

Views: 134

Answers (1)

alexblae
alexblae

Reputation: 746

As ekhumoro already pointed out, your widget needs to be a child of your mainWindow. However, I do not think that you need to call show for the widget, since it anyways gets called as soon as its parent (MainWindow) calls show. As mata pointed out correctly, the proper way to add a Widget to a MainWindow instance is to use setCentralWidget. Here is a working example for clarification:

import sys
from PyQt4 import QtGui, QtCore

class Form(QtGui.QWidget):

    def __init__(self, parent):
        super(Form, self).__init__(parent)
        self.lbl = QtGui.QLabel("Test", self)

class MainWindow(QtGui.QMainWindow):

    def __init__(self, parent=None):

        super(MainWindow, self).__init__()
        self.setGeometry(50, 50, 1600, 900)
        new_window = Form(self)
        self.setCentralWidget(new_window)
        self.show()

def main():
    app = QtGui.QApplication(sys.argv)
    main_window = MainWindow()
    sys.exit(app.exec_())    

if __name__ == "__main__":
    main()

Upvotes: 1

Related Questions