In the previous chapter, we saw 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 to serve the purpose of the application. A main window provides a framework to build an application's user interface. In this chapter, we shall discuss the creation of a main window application with its predefined components. We will also discuss layout management in a windowed application.
PySide provides a class, named PySide.QtGui.QMainWindow
, that is derived from QWidget
and its related classes for main-window management. QMainWindow
has its own layout to which you can add toolbars, a menu bar, a 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 that is similar to the QWidget
class:
PySide.QtGui.QMainWindow([QWidget * parent = 0, Qt::WindowFlags flags = 0)
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 QMainWindow,QApplication # Our main window class class MainWindow(QMainWindow): # Constructor function def __init__(self): super(MainWindow,self).__init__() self.initGUI() def initGUI(self): self.setWindowTitle("Main Window") self.setGeometry(300, 250, 400, 300) self.show() if __name__ == '__main__': # Exception Handling try: myApp = QApplication(sys.argv) mainWindow = MainWindow() 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 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.