PySide GUI Application Development - Second Edition - Sample Chapter
PySide GUI Application Development - Second Edition - Sample Chapter
ee
Second Edition
Elegantly-built GUI applications are always a massive hit
among users. PySide is an open source software project
that provides Python bindings for the Qt cross-platform UI
framework. Combining the power of Qt and Python, PySide
provides easy access to the Qt framework for developers
and also acts as an excellent application development
platform.
$ 29.99 US
19.99 UK
P U B L I S H I N G
Gopinath Jaganmohan
Venkateshwaran Loganathan
pl
C o m m u n i t y
Sa
m
Second Edition
This book will take you through everything you need to know
to develop UI applications. You will learn about installing
and building with PySide in various major operating systems
as well as the basics of GUI programming. The book will
then move on to discuss event management, signals and
slots, and the widgets and dialogs available with PySide.
Database interaction and manipulation is also covered.
E x p e r i e n c e
D i s t i l l e d
Preface
The aim of this book is to introduce you to developing GUI applications in an easy
way. Python is easy to learn and use, and its programs are relatively short compared
to those written in any other programming languages, such as C++, and Java. It is
supported by a large set of dynamic libraries and bindings that make it efficient to
develop very complex applications in an efficient manner. This book will introduce
you to user interface programming and its components. You will be able to develop
real-time applications in a shorter time after reading this book. The second edition.
Preface
Chapter 5, Dialogs and Widgets, details the built-in dialog boxes for applications,
introduces how to create customized dialogs, and then takes a look at the various
widgets that are available in PySide. By the end of this chapter, you will learn about
creating your own customized widgets and dialogs.
Chapter 6, Database Handling, explains how connecting to a database is evident for
almost all applications. This chapter is dedicated to explaining how to connect to a
database and execute queries on it. It also deals with the presentation of data in table
and form views. By the end of this chapter, you will know more about interacting
with databases and viewing data from them.
[1]
Introducing PySide
Many of the modern programming languages are backed up by a set of libraries
(commonly referred to as toolkits) to create GUI applications, such as Qt, Tcl/Tk, and
so on. PySide is a Python binding of the cross-platform GUI toolkit Qt, and it runs on
all platforms that are supported by Qt, including Windows, Mac OS X, and Linux. It
is one of the alternatives to toolkits such as Tkinter for GUI programming in Python.
PySide combines the advantages of Qt and Python. A PySide programmer has
all the power of Qt, but it is able to exploit it with the simplicity of Python.
PySide is licensed under the LGPL version 2.1 license, allowing both Free/Open
Source software and proprietary software development. PySide is evolving
continuously, like any other open source product, and you are free to contribute
to its development. Some of the applications, such as matplotlib, PhotoGrabber,
QBitTorrent, Lucas Chess, Fminer and so on, certify the wide spread usage of PySide
in the software industry.
Hello, GUI
In computing terms, GUI (pronounced as gooey, or Graphical User Interface) is
used to denote a set of interfaces with computing systems that involves user-friendly
images rather than boring text commands. GUI comes to the rescue of the numerous
command-line interfaces that have always been coupled with a steep learning curve
because learning and mastering commands requires a lot of effort due to their
nonintuitive nature. Moreover, GUI layers make it easy for the end users to fulfill
their needs without knowing much about the underlying implementation, which is
unnecessary for them.
[2]
Chapter 1
Every other application in the modern world is designed with interactive graphics
to attract the end users. Simplicity and usability are the two main ingredients for
a successful GUI system. The demanding feature of a GUI is to allow the user to
concentrate on the task at hand. To achieve this, it must serve the interaction between
the human and the computer, and make it no less than seamless and flowing.
Therefore, learning to create GUIs will not only make you a successful developer, but
it will also help in getting some revenue for yourself.
At a very basic level, a GUI is seen as a window (visibly noticeable or not) consisting
of the following parts: controls, menu, layout, and interaction. A GUI is represented
as a window on the screen and contains a number of different controls, as follows:
Menu: This is usually situated under the top frame of the GUI window and
presents to the users some choices to control the application. The top frame
can also have buttons to hide, resize, or destroy the windows, which are,
again, controls.
Layout: This is the way that the controls are positioned, which is very
important in good GUI design.
Interaction: This happens in the way of I/O devices, such as a mouse and
keyboard.
[3]
Setting up PySide
This is your first step in this series of learning. PySide is compatible with Python
2.6 or later and Qt 4.6 or better. So, before getting to install PySide, we must make
sure that minimum version compatibility is achieved. This section will teach you
two ways of installing PySide. One, being the most common and easiest way, is
using simple point and click installers and package managers. This will install
the most stable version of PySide on your system, which you can comfortably use
without worrying too much about the stability. However, if you are an advanced
programmer, you may prefer to build PySide from scratch from the latest builds that
are available when you are reading this book. Both these methods are explained here
for Windows, Mac OS X, and Linux systems, and you are free to choose your own
setup style.
2. Run the downloaded installer executable, which will automatically detect the
Python installation from your system
3. You are given an option to install PySide on the default path or at the path of
your choice
4. On clicking Next in the subsequent windows, and finally clicking Finish,
PySide is installed successfully on your system
Download the latest version that is compatible with your system and perform a
similar installation as explained in the previous section.
[4]
Chapter 1
You can also choose to install PySide from the command line with the help of
Homebrew or using MacPorts. The commands, respectively, are as follows:
brew install pyside
port-install pyXX-pyside
On an RPM-based system, you can use the RPM-based distribution, yum, as follows:
yum install python-pyside pyside-tools
If you want to make sure that PySide is installed properly on your system, issue the
following commands in the Python shell environment, as shown in Figure 1. The
import pyside command should not return any errors.
PySide.__version__ should output something similar to 1.1.2:
Figure 1
[5]
Visual Studio Express 2008 (Python 2.6, 2.7, or 3.2) / Visual Studio Express
2010 (Python 3.3) [http://www.microsoft.com/visualstudio/eng/
products/visual-studio-express-products]
CMake [http://www.cmake.org/cmake/resources/software.html]
Git [http://git-scm.com/download/win]
OpenSSL [http://slproweb.com/products/Win32OpenSSL.html]
(Optional)
Make sure that the Git and cmake executables are set in your system path. Now,
perform the following steps to start building PySide:
1. Git Clone the PySide repository from GitHub, as follows:
c:/> git clone https://github.com/PySide/pyside-setup.git pysidesetup
4. Upon successful installation, the binaries can be found in the dist sub-folder:
c:\pyside-setup\dist
On completion of these steps, the PySide should have been successfully built on your
system.
[6]
Chapter 1
Prerequisites
software.html]
org/XSLT/downloads.html]
www.python.org/download/]
Building PySide
PySide is a collection of four interdependent packages, namely API Extractor,
Generator Runner, Shiboken Generator, and Pyside Qt bindings. In order to build
PySide, you have to download and install these packages in that order:
API Extractor: This is a set of libraries that is used by the binding generator
to parse the header and type system files to create an internal representation
of the API [https://distfiles.macports.org/apiextractor/].
Generator Runner: This is the program that controls the bindings generation
process according to the rules given by the user through headers, type
system files, and generator frontends. It is dependent on the API Extractor
[https://distfiles.macports.org/generatorrunner/].
Shiboken Generator: This is the plugin that creates the PySide bindings
source files from Qt headers and auxiliary files (type systems, global.h, and
glue files). It is dependent on Generator Runner and API Extractor [https://
distfiles.macports.org/py-shiboken/].
PySide Qt Bindings: This is a set of type system definitions and glue codes
that allows generation of Python Qt binding modules using the PySide
tool chain. It is dependent on Shiboken and Generator Runner [https://
distfiles.macports.org/py-pyside/].
[7]
Always, make sure that you have downloaded and built these packages in this
order because each of these packages is interdependent. The build steps for each
of these are:
1. Unzip the downloaded packages and change into the package directory:
tar xvf <package_name>
cd <package_directory>
2. Create a build directory under the package directory and enter that directory:
mkdir build && cd build
Please note that you require sudo permissions to install the packages.
5. To update the runtime linker cache, issue the following command:
sudo ldconfig
Once you complete these steps in this order for each of these packages, PySide
should be successfully built on your system.
Mac OS X
Building PySide on a Mac system follows the same procedure as the Linux system
except that Mac needs Xcode-Developer Tools to be installed as a prerequisite.
If you are installing the libraries in a nondefault system directory (other
than /usr/local), you may have to update the DYLD_LIBRARY_PATH
by typing the following command:
export DYLD_LIBRARY_PATH=~/my_dir/install/lib
Chapter 1
There are basically two ways that are widely followed when importing modules in
Python. The first is to use a direct import <module> statement. This statement will
import the module and creates a reference to the module in the current namespace.
If you have to refer to entities (functions and data) that are defined in module, you
can use module.function. The second is to use from module import*. This statement
will import all of the entities that the module provides and set up references in the
current namespace to all the public objects defined by that module. In this case,
referencing an object within the module will boil down to simply stating its literal
name in code.
Therefore, in order to use PySide functions and data in your program, you have to
import it by saying either import PySide or from PySide import*. In the former
case, if you have to refer to some function from PySide you have to prefix it with
PySide, such as PySide.<function_name>. In the latter, you can simply call the
function by <function_name>. Also, please note that in the latter statement, * can be
replaced by specific functions or objects. The use of * denotes that we are trying to
import all the available functions from that module. Throughout this book, I would
prefer to use the latter format as I do not have to prefix the module name every time
when I have to refer to something inside that module.
Now, let's get into the working of the code. We start with importing the necessary
objects into the program.
Lines 1, 2 and 3 imports the necessary modules that are required for the program.
Python is supported with a library of standard modules that are built into the
interpreter and provide access to operations that are not a part of the core language.
One such standard module is sys, which provides access to some variables and
functions that are used closely by the interpreter. In the preceding program, we need
the sys module to pass command-line arguments sys.argv as a parameter to the
QApplication class. It contains the list of command-line arguments that are passed
to a Python script. Any basic GUI application that uses PySide should have two
classes imported for basic functionality. They are QtCore and QtGui. The QtCore
module contains functions that handle signals and slots and overall control of the
application, whereas QtGui contains methods to create and modify various GUI
window components and widgets.
[ 10 ]
Chapter 1
[ 11 ]
Here, suite is an indented block of statements. We can also have a set of try, except
block in a try suite. The former except statement provides a specific exception class
that can be matched with the exception that is raised. The latter except statement is
a general clause that is used to handle a catch-all version. It is always advisable to
write our code in the exception encapsulation.
In the previous example, consider that we have missed instantiating the appLabel
object. This might cause an exception confronting to a class of exception called
NameError. If we did not encapsulate our code within the try block, this raises a
runtime error. However, if we had put our code in a try block, an exception can be
raised and handled separately, which will not cause any hindrance to the normal
execution of the program. The following set of code explains this with the possible
output:
# Import the necessary modules required
import sys
from PySide.QtCore import *
from PySide.QtGui import *
[ 12 ]
Chapter 1
# Main Function
if __name__ == '__main__':
# Create the main application
myApp = QApplication(sys.argv)
# Create a Label and set its properties
try:
#appLabel = QLabel()
appLabel.setText("Hello, World!!!\n Look at my first app using
PySide")
appLabel.setAlignment(Qt.AlignCenter)
appLabel.setWindowTitle("My First Application")
appLabel.setGeometry(300, 300, 250, 175)
# Show the Label
appLabel.show()
# Execute the Application and Exit
myApp.exec_()
sys.exit()
except NameError:
print("Name Error:", sys.exc_info()[1])
pass
In the preceding program, if we did not handle the exceptions, the output would be
as shown in the figure:
[ 13 ]
Conversely, if we execute the preceding code, we will not run into any of the errors
shown in the preceding figure. Instead, we will have captured the exception and
given some information about it to the user, as follows:
Summary
The combination of Qt with Python provides the flexibility of Qt developers,
develops GUI programs in a more robust language, and presents a rapid application
development platform available on all major operating systems. We introduced to
you the basics of PySide and its installation procedure on Windows, Linux, and
Mac systems. We went on to create our first application, which introduced the main
components of creating a GUI application and the event loop. We have concluded
this chapter with an awareness on how to introduce exception handling as a best
practice. Moving on, we are set to create some real-time applications in PySide.
[ 14 ]
www.PacktPub.com
Stay Connected: