In the previous chapter, we have seen how to create windows using widgets. Most of the GUI applications that we use today are main window styled applications, which have a menu bar, toolbars, a status bar, a central widget, and optional dock widgets. Generally, an application will have a single main window and a collection of dialogs and widgets for serving the purpose of the application. A main window provides a framework for building an application's user interface. In this chapter, we shall discuss the creation of a main window application with its predefined components and also discuss the layout management in a windowed application.
PySide provides a class named PySide.QtGui.QMainWindow derived from QWidget, and its related classes for main window management. QMainWindow has its own layout to which you can add toolbars, menu bar, status bar, dock widgets, and a central widget. The layout description of a main window is as shown in the following figure:
The central widget can be of any standard or custom widgets, say for example, QTextEdit
or a QGraphicsView
. Creating a main window without a central widget is not supported. Moving on, we will examine how to create a main window and will cover how to add its components one by one.
As a first step, we will start with creating a main window by subclassing the QMainWindow
class. The QMainWindow
class has a constructor function similar to QWidget
class.
The parent can be any valid QWidget
object and flags can be a valid combination of Qt.WindowFlags
. The following code excerpt explains how to create a main window application at a very basic level.
# Import required modules import sys, time from PySide.QtGui import QApplication, QMainWindow class MainWindow(QMainWindow): """ Our Main Window Class """ def __init__(self): """ Constructor Fucntion """ QMainWindow.__init__(self) self.setWindowTitle("Main Window") self.setGeometry(300, 250, 400, 300) if __name__ == '__main__': # Exception Handling try: myApp = QApplication(sys.argv) mainWindow = MainWindow() mainWindow.show() myApp.exec_() sys.exit(0) except NameError: print("Name Error:", sys.exc_info()[1]) except SystemExit: print("Closing Window...") except Exception: print(sys.exc_info()[1])
This will create a very minimal and a basic main window with no other components as shown in the following screenshot. In the forthcoming sections, we will see how to add these components in the main window: