Chapter 2. Entering through Windows

The main part of any GUI program is to create windows and define functionalities around it. We will start exploring ways to create windows and customize it in this chapter and will move on to create a real-time windows application in the next chapter.

The widget is the center of the user interface. It receives the user inputs from mouse, keyboard, and other events, of the window system, and paints a representation of itself on the screen. Every widget is rectangular, and sorted in a Z-order. A widget is clipped by its parent and by the widgets in front of it. A widget that does not have a parent is called a window and is always independent. Usually, windows have a frame and a title bar at the least but it is possible to create them without these by setting some windows flags. This chapter explains how to create simple windows using QWidget and also how to create some widely used widgets. The code snippets that are explained from this chapter onwards will be based on Object-Oriented Design principles.

Creating a simple window

The QWidget is the base class for all the user interface classes. A widget can be a top-level widget or a child widget contained in a top-level or parent widget. Now, let's create a top-level window using QWidget. The constructor of the QWidget class takes two optional parameters, parent and flags. The parent can be a QWidget object and flags can be a combination of PySide.QtCore.Qt.WindowFlags.

# Import required modules
import sys
import time
from PySide.QtGui import QApplication, QWidget

class SampleWindow(QWidget):
    """ Our main window class
    """

    # Constructor function
    def __init__(self):
        QWidget.__init__(self)
        self.setWindowTitle("Sample Window")
        self.setGeometry(300, 300, 200, 150)
        self.setMinimumHeight(100)
        self.setMinimumWidth(250)
        self.setMaximumHeight(200)
        self.setMaximumWidth(800)
        

if __name__ == '__main__':
    # Exception Handling
    try:
        myApp = QApplication(sys.argv)
        myWindow = SampleWindow()
        myWindow.show()
        time.sleep(3)
        myWindow.resize(300, 300)
       myWindow.setWindowTitle("Sample Window Resized")
        myWindow.repaint()
        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])

In this sample program, we create a window, set its minimum and maximum size and repaint the window with different dimensions after a short period. If you look at the code closely, you may analyze that the code follows exception handling mechanism and object-oriented principles as explained earlier.

The main idea in the earlier program is to introduce you with creating classes and objects and work around them since programming in PySide indirectly implies programming using OO principles. PySide libraries follow the OO principles and so do we. Our sample window is instantiated with the class that we have declared for this purpose. The class SampleWindow is inherited from the PySide.QtGui.QWidget class. So, all the properties of QWidget can be applied to our SampleWindow class also. The __init__ function is called the constructor to be shown when an object is instantiated. While instantiating the object, we also call the constructor function of its super class for proper instantiation and hence the line QWidget.__init__(self). The methods that follow this line are all inherited from the QWidget class. The functions setMinimumHeight, setMinimumWidth set the window to minimum size and cannot be shrinked further. Similarly, the window cannot be extended beyond the maximum size specified by the functions setMaximumHeight and setMaximumWidth.

Our main function is encapsulated in a try, catch block to deal with any unexpected exceptions that may occur. As explained in the previous chapter, every PySide application must create a main application object. So, we start with creating an object for the QApplication class. Then, we create an object for our custom defined class SampleWindow. At this point, the __init__ function is called and all the properties defined for our sample window are set. We paint the window on the screen by calling the show function on the SampleWindow object. The lines that follow are just an example to show that we can repaint the windows with different dimensions at any point during the execution of the program. So, we hold on (sleep) for 3 seconds, resize the window and repaint it on the screen. Now, execute the code and have some fun.

On executing the program, you will be shown a window as shown in the following image. This window will get resized after 3 seconds. Also, try to resize the window by dragging its corners. You may notice that the window cannot be shrunk or expanded beyond the minimum and maximum metrics set in our earlier code. You might not initially see a window when executing this program on an XWindow based system such as Linux, because the main application loop has not been called yet, so none of the objects has been really constructed and buffered out to the underlying XWindow system.

Creating a simple window

The following figure is the screenshot of the final output that you will see:

Creating a simple window
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.51.157