Data Types and Data Structures

In this chapter, we begin a Python conversion course that shows non-Python programmers how to program with Python. We introduce some fundamental data types and data structures, as well as some of Python's procedural syntax. The approach taken throughout is to emphasize realistic code like that used in practice, rather than giving the formal definitions and explanations that are already available in the documentation that is supplied with Python and available online at http www.python.org. Hie...

Methods and Special Methods

We will begin by looking at a class that uses accessor methods to get and set the value of attributes, rather than using direct attribute access. self.width width self.height height def getWidth(self) return self.width def setWidth(self, width) self.width width def getHeight(self) return self.height def setHeight(self, height) self.height height return self.getWidth() * self.getHeight() We have chosen to use a Java-style naming convention for both getters and setters. Now we can write code like...

Currency Converter in Lines

One small utility that is often useful is a currency converter. But since exchange rates frequently change, we cannot simply create a static dictionary of conversion rates as we did for the units of length in the Length class we created in the previous chapter. Fortunately, the Bank of Canada provides exchange rates in a file that is accessible over the Internet, and which uses an easy-to-parse format. The rates are sometimes a few days old, but they are good enough for estimating the cash...

The Structure of the Book

Part I is primarily a rapid conversion course aimed at non-Python programmers who are familiar with an object-oriented language, although it also has some clearly marked PyQt content. Because the core Python language is mostly simple and is quite small, these chapters can teach the basics of Python to a sufficient extent that real Python applications can be written. If you think that you can pick up the Python syntax simply through reading it, you might be...

Animation and Complex Shapes

In the preceding section, we looked at a graphics view application in which user interaction was central. In this section, we will look at a very different kind of application, one where we simulate a population of creatures, multipedes, by visualizing each member of the population using a set of graphics items, as shown in Figure 12.4. Each multipede has internal timers. At each time interval the multipede moves, and if it has collisions, its coloring is changed slightly, and eventually it...

Classes and Modules

Python fully supports procedural and object-oriented programming, and leaves us free to use either approach, or to combine the two. So far we have done procedural programming, although we have already used some Python classes for example, the str string class. What we have not yet done is defined our own classes. In this chapter we will learn how to create classes and methods, and how to do object-oriented programming with Python. And in all subsequent chapters, we will almost always use an...

Eric4 Ide Applications

Pyqt Gui Prototyping

This book teaches how to write GUI applications using the Python programming language and the Qt application development framework. The only essential prior knowledge is that you can program in some object-oriented programming language, such as C , C , Java, or of course, Python itself. For the rich text chapter, some familiarity with HTML and with regular expressions is assumed, and the databases and threading chapters assume some basic knowledge of those topics. A knowledge of GUI programming...

Data Container Responsibilities

The application's data container is responsible for holding all the data items, that is, the movie records, and for saving and loading them to and from disk. We saw in the preceding section when we looked at the MainWin-dow.updateTable method how the container could be iterated over using a for loop to get all the movies so that they could be displayed in the application's QTableWidget. In this section, we will look at the functionality provided by the moviedata module, including the data...

Events the Clipboard and Drag and Drop

In this short chapter we begin by describing the key concepts involved in event handling. In the second section we build on this knowledge to show how to control a widget's behavior and appearance by reimplementing low-level event handlers. Later chapters build on the material covered in the first two sections, particularly Chapter 11, which shows how to create custom widgets. The chapter's third section shows how to use the clipboard, and in particular how to pass and retrieve plain text,...

Creating and Using Actions

The code we saw earlier for creating a file new action required six lines to create and set up the action. Most main-window-style applications have scores of actions, so typing six lines for each one would soon become very tedious. For this reason, we have created a helper method which allows us to reduce the code for creating actions to just two or three lines. We will look at the helper, and then see how it is used in the main window's initializer. def createAction self, text, slot None,...

Implementing a Secondary Thread

The Page Indexer's secondary thread is implemented in the Walker class in the file chap19 walker.py. The class is a QThread subclass that uses a QMutex to protect accesses that it makes to its own private data, and that uses the QReadWriteLock passed to it to protect accesses to data it shares with the primary thread. COMMON_WORDS_THRESHOLD 250 MIN_WORD_LEN 3 MAX_WORD_LEN 25 INVALID_FIRST_OR_LAST frozenset 0123456789_ STRIPHTML_RE re.IGNORECASE re.MULTILINE ENTITY_RE SPLIT_RE re.compile r W ,...

Testing Dialogs

Since any PyQt widget, including any dialog, can be used as a top-level window in its own right, it is easy to test a dialog by instantiating it and starting the event loop. Often, though, we need to do a bit more. For example, we may need to set up some initial data, or provide methods to receive the dialog's signals so that we can see that they are working correctly. In the case of the Find and Replace dialog, we need some initial text, and we need to check that the connections work and that...

Data Handling and Custom File Formats

Most applications need to load and save data. Often the data format is predetermined because the application is reading data produced by some other application over which it has no control. But for applications where we create our own file formats, a lot of options are available. In Chapter 6 we created a main-window-style application from which we learned how to create menus and toolbars, and how to handle file loading and saving. In this chapter we will work on another main-window-style...

Enabling and Disabling Actions

Sometimes particular actions are applicable only in certain circumstances. For example, it doesn't make much sense to allow file save on a document with no unsaved changes, or, arguably, to allow file save as on an empty document. Similarly, neither edit copy nor edit cut makes sense if there is no selected text. One way to deal with this is to leave all the actions enabled all the time, but to make sure that they do nothing in cases where they don't make sense for example, if we call...

Inheritance and Polymorphism

Just as we would expect from a language that supports object-oriented programming, Python supports inheritance and polymorphism. We have already used inheritance because the classes we have created so far have inherited object, but in this section we will go into more depth. All Python methods are virtual, so if we reimplement a method in a base class the reimplemented method will be the one that is called. We will see shortly how we can access base class methods, for example, when we want to...

Main Window Responsibilities

The main window is usually given responsibility for offering the user the highlevel file-handling actions, and for presenting the application's data. In this section, we will focus particularly on the file actions, since they differ from what we did in Chapter 6's Image Changer application and they are more representative of what happens in larger applications. We will also look at how the data is presented to the user. In the My Movies application, the data is held in a container a...

Writing and Reading Using QText Stream

The code for writing in text format using QTextStream is very similar to the code we used for writing using QDataStream. def saveQTextStream self error None fh None try if not fh.open QIODevice.WriteOnly raise IOError, unicode fh.errorString stream QTextStream fh stream.setCodec CODEC stream lt lt MOVIE lt lt movie.title lt lt n lt lt movie.year lt lt lt lt movie.minutes lt lt lt lt movie.acquired.toString Qt.ISODate lt lt n NOTES if not movie.notes.isEmpty stream lt lt n lt lt movie.notes...

Bytestrings Unicode Strings and QStrings

There are two built-in string types in Python str which holds bytes, and unicode which holds Unicode characters. Both types support a common set of string-processing operations. Like numbers, Python strings are immutable. They are also sequences, so they can be passed to functions that accept sequences and can use Python's sequence operations, for example, the len QString function which returns the length of a sequence. PyQt provides a third string 28 type, QString. If we only deal with 7-bit...

Networking

Pyqt5 Qudpsocket Client Example

Pycrypto-2.0.1.tar.gz target source source.rfind 1 name, message urllib.urlretrieve source, target The name holds the name that the source was saved under it will be the same as target in this case, but if no target is specified it will be a generated name for example, tmp tmpX-R8z3.tar.gz. For an HTTP download, the message is an httplib.HTTPMessage instance that contains the relevant HTTP headers. Python's urllib and urllib2 standard library modules are very versatile. They can use the FTP and...

Selected PyQt Class Hierarchies

Qprinter Sample

- QComboBox QFontComboBox i- QAbstractListModel - QStringListModel - QDirModel Figure C.4 Selected classes from the QAbstractltemModel hierarchy i- QAbstractPrintDialog QPrintDialog Figure C.5 Selected classes from the QDialog hierarchy - QAbstractSockeT - QIODevice QBuffer Figure C.6 Selected classes from the QIODevice hierarchy Figure C.8 Selected classes from the QEvent hierarchy Figure C.8 Selected classes from the QEvent hierarchy QAbstractGraphicsShapeItem -- QGraphicsPolygonItem Figure...

Implementing Dialogs

When we create a user interface with Qt Designer, we create a subclass using multiple inheritance in which we put the code we need to give the user interface the behavior we need. The first class we inherit is QDialog. If we were using the Widget template our first inherited class would be QWidget, and if we were using the Main Window template our first inherited class would be QMainWin-dow. The second class we inherit is the class that represents the user interface we designed using Qt...

Installing on Linux and Unix

If you are running Kubuntu 7.04 Fiesty Fawn and later , you already have PyQt4 installed So, you only need to install the book's examples see page 573 , and the documentation packages python-doc and python-qt4-doc. If mkpyqt.py does not work, you will have to edit the mkpyqt.py file and at least hard-code the path to pyuic4. For Linux and most other Unixes that don't have PyQt4 preinstalled, there are four tools to install the Qt C application development framework, the Python interpreter and...

Creating Composite Widgets

A composite widget is a widget that is composed of two or more other widgets. We are already experienced composite widget creators For example, every dialog we have created is a composite widget. We are dedicating some space to a topic we have already covered because unlike the dialogs we created earlier which were QDialog subclasses , we want to create composite widgets that are not dialogs, and that instead can be used inside dialogs or as a main window's central widget . The kind of...

Single Document Interface SDI

For some applications, users want to be able to handle multiple documents. This can usually be achieved simply by running more than one instance of an application, but this can consume a lot of resources. Another disadvantage of using multiple instances is that it is not easy to provide a common Window menu that the user can use to navigate between their various documents. There are three commonly used solutions to this. One is to use a single main window with a tab widget, and with each tab...

Writing and Reading Using the pickle Module

Python's standard pickle module, and its faster cPickle counterpart, can save arbitrary Python data structures to disk and load them back again. These modules provide exactly the same functions and functionality. The only difference between them is that the pickle module is implemented purely in Python, and the cPickle module is implemented in C. These modules only understand the data types in the Python standard library, and classes that are built from them. If we want to pickle PyQt-specific...

Installing on Windows

For Windows, there are four tools to install a C compiler, the Qt C application development framework, the Python interpreter and its accompanying libraries, and PyQt4 which includes SIP in the Windows binary package . We assume that the GPL editions are being used, in which case the only C compiler that will work with Qt is MinGW. Visual C can be used only with the commercial editions of Qt and PyQt and the instructions for installing them are provided when you buy them. SIP is a tool used to...

Tab Widgets and Stacked Widgets

Some dialogs require so many widgets to present all the options that they make available that they become difficult for the user to understand. The most obvious way to deal with this is to create two or more dialogs and to divide the options between them. This is a good approach when it is possible since it minimizes the demands made on the user, and may also be easier from a maintenance point of view than a single complex dialog. But often we need to use a single dialog because the options we...

Printing Documents

Getting printed output from PyQt applications can be achieved in a number of ways. One approach is to produce output in a form that another program can print, such as producing HTML for a Web browser to print or SVG for an SVG-savvy drawing program to print. From Qt 4.1, users can produce PDF documents through the Print dialog by H checking the print to file option. It is also possible to produce PDF documents programmatically. For example, assuming that document is a QTextDocument These...

Multiple Document Interface MDI

Qworkspace Widget

MDI offers many benefits compared with SDI or with running multiple application instances. MDI applications are less resource-hungry, and they make it much easier to offer the user the ability to lay out their document windows in relation to each other. One drawback, however, is that you cannot switch between MDI windows using Alt Tab Command Tab on Mac OS X , although this is rarely a problem in practice since for MDI applications, programmers invariably implement a Window menu for navigating...

Splitters

Qlistwidget

Some main-window-style applications need to use more than one widget in their central area. Two common types of applications that need to do this are email clients and network news readers. There are three approaches we can take to handle this. One is to create a composite widget, that is, a widget that Compos is composed of other widgets created and laid out like a dialog, but inheriting from QWidget instead of QDialog , and use this widget as the main window's central widget. Another approach...

Resource Files

Unfortunately, there is a small problem with the code we have written. It assumes that the application's working directory is the directory where it is located. This is the normal case under Windows where the .pyw or a shortcut to it is clicked or double-clicked . But if the program is executed from the command line from a different directory for example, . chap06 imagechanger.pyw none of the icons will appear. This is because we gave the icon's path as images, that is, a path relative to the...

Extension Dialogs

Pyqt Noframe

There is another approach that we can take for complex dialogs extension dialogs. These are typically used for cases where the dialog has simple and advanced options. Initially the dialog is shown with the simple options, but a toggle button is provided to show or hide the advanced options. The extension dialog shown in Figure 9.3 shows the extra checkboxes when the More toggle button is depressed. Any QPushButton can be made into a toggle button by calling setCheckable True on it, or by...

Selected PyQt Widgets

Qgraphics Tutorial

The screenshots shown here were taken on Linux using KDE to provide an eye-pleasing consistency. In the body of the book, screenshots are shown for Windows, Linux, and Mac OS X, generally varying from chapter to chapter. This widget can be used as a display widget, although it was designed primarily as an input widget through which the user can choose a particular date. The widget's display is highly configurable for example, week numbers can be displayed or not, day names can be represented by...

Signals and Slots

Every GUI library provides the details of events that take place, such as mouse clicks and key presses. For example, if we have a button with the text Click Me, and the user clicks it, all kinds of information becomes available. The GUI library can tell us the coordinates of the mouse click relative to the button, relative to the button's parent widget, and relative to the screen it can tell us the state of the Shift, Ctrl, Alt, and NumLock keys at the time of the click and the precise time of...

Main Windows

Most applications are main-window-style applications, that is, they have a menu bar, toolbars, a status bar, a central area, and possibly dock windows, to provide the user with a rich yet navigable and comprehensible user interface. In this chapter, we will see how to create a main-window-style application which demonstrates how to create and use all of these features. Figure 6.1 The Image Changer application Figure 6.1 The Image Changer application We will use the Image Changer application...

Printing Images

Printing images in general is just as simple as printing scenes. Here is a printImage method that will print any QImage or QPixmap both of which can load .bmp, .png, .jpg, and various other graphics file types on a single page, assuming that printer is a QPrinter def printImage image, printer, scaleToFillPage False dialog QPrintDialog printer if dialog.exec_ painter QPainter printer rect painter.viewport size image.size size.scale rect.size , Qt.KeepAspectRatio painter.setViewport rect.x ,...

Installing on Mac OS X

Mac Pyqt Xcode

To install PyQt on Mac OS X, you must already have the Xcode tools installed. This is because a compiler and build tool are required to install PyQt. Xcode is a very large package, normally supplied on a separate developer's CD provided with the machine it is also available online from http developer.apple. com tools xcode. The following instructions assume that Xcode is already installed. Although Macs are normally supplied with a version of Python preinstalled, it may be an old version, in...

Printing Documents Using QPainter

We will conclude this section by looking at how to print using QPainter. Taking this approach means that we have the chore of doing all the position calculations ourselves, but also the benefit of being able to draw anything anywhere on the page, without being limited to what can be represented by HTML or by a QTextDocument. In addition, the painting itself uses the same methods and techniques that we have seen in the previous two chapters, since PyQt has a uniform approach to painting whether...

An Expression Evaluator in Lines

Qtextbrowser

This application is a complete dialog-style application written in 30 lines of code excluding blank and comment lines . Dialog-style means an application that has no menu bar, and usually no toolbar or status bar, most commonly with some buttons as we will see in the next section , and with no central widget. In contrast, main window-style applications normally have a menu bar, toolbars, a status bar, and in some cases buttons too and they have a central widget which may contain other widgets,...

Creating Custom Delegates

If we want to exercise complete control over the presentation and editing of data items, we must create a custom delegate. A delegate can be used purely to control appearance for example, for read-only views or to control editing by providing custom editors, or both. Wartsila-Sulzer RTA96-C main engine, 109,000 hp Figure 14.4 A custom delegate in action Figure 14.4 looks similar to earlier screenshots, with the only noticable difference being that the description text is properly formatted...

Writing XML

If we have read an XML document into a QDomDocument, or if we have created and populated a QDomDocument in code, the easiest way to save the document to disk is to use QDomDocument.toString to get a QString of the entire document in XML format, and to save the string to disk. In practice, though, we often use XML only as a data-interchange format, and hold our data in custom data structures. In these cases, we need to write the XML ourselves, and that is what we will look at in a moment. In...

Reading and Parsing XML with PyQts SAX Classes

Importing XML using a SAX parser works quite differently than using a DOM parser. With SAX, we define a handler class that implements just the methods that we are interested in, and then give an instance of the handler to the SAX parser to use as it parses the XML. Parsing is not done in one go as it is with DOM, but rather piece by piece, with our handler's methods being called when the data they handle is encountered. Any methods that we do not implement are provided by the base class, and in...

Saving and Loading Text Files

PyQt and the Python standard library provide facilities for writing and reading text files. PyQt uses the QTextStream class, and the Python standard library uses the codecs module. Plain text formats are usually human-readable, in a text editor, for example, and are usually easy to write. Any kind of data can be written as plain text one way or another. Numbers and dates can be written quite easily and compactly by using their string representations, and other types, such as images, can be...

Designing User Interfaces

Pyqt4 Pushbutton

Before we can begin we must start Qt Designer. On Linux, run designer amp in a console assuming it is in your path , or invoke it from your menu system. On Windows XP, click Start Qt by Trolltech Designer, and on Mac OS X launch it using Finder. Qt Designer starts with a New Form dialog click Dialog with Buttons Bottom and then click Create. This will create a new form with a caption of untitled, and with the QDialogButtonBox as shown in Figure 7.2. Figure 7.2 A dialog with buttons bottom...

Printing Documents Using QText Cursor and QText Document

We will now see how to achieve the same thing by creating a QTextDocument programmatically, rather than by creating an HTML string and using set-Html . The code is more than twice as long as is the code that uses QPainter that follows , but we should not infer from this particular example that these techniques will necessarily require more code in general. dialog QPrintDialog self.printer, self if not dialog.exec_ return logo QPixmap logo.png headFormat QTextBlockFormat We iterate over each...

Exception Handling

Python Exception Hierarchy

Many primers push exception handling quite far back, often after covering object-oriented programming. We put them here in the control structures chapter because exception handling is relevant in both procedural and object-oriented programming, and because exception handling can cause the flow of execution to change dramatically, which certainly qualifies exception handlers as a kind of control structure. An exception is an object that is raised or thrown under some specific circumstances. When...

Printing Documents Using HTML and QText Document

The first approach we will show involves creating a string containing HTML, and using a QTextDocument to render the HTML to a QPrinter. The printVia-Html method is quite long, so we will look at it in three parts. def printViaHtml self html u date address lt br gt contact Qt.escape statement.contact balance statement.balance html lt p align right gt lt img src ' logo.png' gt lt p gt lt p align right gt Greasy Hands Ltd. lt br gt New Lombard Street lt br gt London lt br gt WC13 4PX lt br gt s lt...

Introduction to GUI Programming

In this chapter we begin with brief reviews of three tiny yet useful GUI applications written in PyQt. We will take the opportunity to highlight some of the issues involved in GUI programming, but we will defer most of the details to later chapters. Once we have a feel for PyQt GUI programming, we will discuss PyQt's signals and slots mechanism this is a high-level communication mechanism for responding to user interaction that allows us to ignore irrelevant detail. Although PyQt is used...

Multithreading

Traditionally, applications have a single thread of execution and perform one operation at a time. For GUI programs this can sometimes be a problem for example, if the user invokes a long-running operation, the user interface might freeze up while the operation is taking place. There are a few solutions that can be tried to eliminate this problem. One simple solution, particularly useful in long-running loops, is to call QAp-plication.processEvents . This method gives the event loop the...

Pyqt Setsortingenabled Qsqlquerymodel

Page size, printer, 400 Page Designer application, 351-368 pageRect QPrinter , 408 paint devices see QImage, QPainter, QPicture, QPixmap, QPrinter, QSvgGenerator, and QWidget paint 461, 486, 489 QGraphicsItem, 366, 368, 374, 377 paintEvent QWidget , 306, 309, 336, 342,480 palette see QPalette palette QApplication, 438, 489 QWidget, 337 parameters, 55, 56 default, 56 keyword, 55, 59-61 passing by value, 57 positional, 55 parent QObject , 433, 504 parent, of widget, 118,119,172,340, 372...

Representing Tabular Data in Trees

Connecting Widgets Pyqt

Suppose we want the user to pick out a data item, but that the item they pick depends on some previous item they picked, which in turn depends on some previous item again. In concrete terms, imagine that we want the user to choose a particular airport first they must choose the country, then the city, and then the airport. This could be done by providing three comboboxes, populating the first with country names, and populating the second with the cities in the current country, and the third...

Ships.shiptablemodel

Like model subclasses, delegates follow a fixed pattern. In the case of delegates for read-only models, the only method we must reimplement is paint . For editable models, we must reimplement createEditor , setEditorData , and setModelData . It is also common to reimplement commitAndCloseEditor if we use QLineEdits or QTextEdits for editing. Finally, it is sometimes necessary to reimplement sizeHint , as we will see. For this section we are using the chap14 ships-delegate.pyw application. This...

Rich Text Line Edit

In some applications it is a requirement that users can enter single lines of rich text. For example, a database application may have a description field where we want the user to be able to use bold, italic, and colors for particular words if they want. We will see examples of this in Chapter 14 and Chapter 16. Unfortunately, PyQt does not provide such a widget. In this subsection we will create a RichTextLineEdit, a subclass of QTextEdit that provides the functionality we need it is shown in...

Drawing A Line Using The Graphics View With Pyqt

The graphics view classes are ideal for situations where we have lots of individual items to draw, from dozens to hundreds of thousands. They are also perfect for when we want to allow the user to interact with items for example, clicking, dragging, and selecting them as well as being ideal for doing animation. Scenes use their own logical coordinate system and contain graphics items. Scenes are viewed using QGraphicsView, and more than one view can be associated with a scene if we want the...

PopUp Alert in Lines

Our first GUI application is a bit odd. First, it must be run from the console, and second it has no decorations no title bar, no system menu, no X close button. Figure 4.1 shows the whole thing. Figure 4.1 The Alert program To get the output displayed, we could enter a command line like this C gt cd c pyqt chap04 C pyqt chap04 gt alert.pyw 12 15 Wake Up When run, the program executes invisibly in the background, simply marking time until the specified time is reached. At that point, it pops up...

Creating a Main Window

For most main-window-style applications, the creation of the main window follows a similar pattern. We begin by creating and initializing some data structures, then we create a central widget which will occupy the main window's central area, and then we create and set up any dock windows. Next, we create actions and insert them into menus and toolbars. It is quite common to also read in the application's settings, and for applications that restore the Figure 6.2 The Image Changer's modules,...

Custom and Interactive Graphics Items

Pyside Move Qgraphicsitem

The predefined graphics items can be made movable, selectable, and focusable by calling setFlags on them with suitable constants. Users can drag movable items with the mouse, and they can select selectable items by clicking them, and by using Ctrl Click to select multiple items. Focusable items will receive key events, but will ignore them unless we create an item subclass with a key event handler. Similarly, we can make items responsive to mouse events by subclassing and implementing...

Qsqltablemodel.setfilter

Radians math , 371, 375 raise_ QWidget , 160,289, 330 raising windows, 160 randint random , 19, 357, 371, 375 range , 39, 50-51, 54 see also xrange raw strings, 157, 220 re module, 219, 220, 554, 556 read-only models, 427 read-only widgets, 421 readAll QIODevice, 254 QTextStream, 384 readBool QDataStream , 245 readDouble QDataStream ,241,245 readIntn QDataStream , 243,245, 360,435 readline codecs ,255 readLine QTextStream , 252, 253, 254 readUIntn QDataStream , 245, 528, 540 recently used...

Using the Clipboard

PyQt provides clipboard support for text in QTextEdit, QLineEdit, QTableWidget, and the other widgets where textual data can be edited. PyQt's clipboard and drag-and-drop systems use data in MIME Multipurpose Internet Mail Extensions format, a format that can be used to store any arbitrary data. Occasionally, it is convenient to pass data to the clipboard or retrieve data from the clipboard directly in code. PyQt makes this easy. The QApplication class provides a static method that returns a...

Creating and Managing Secondary Threads

One common use case for threads in GUI applications is to pass processing on to a secondary thread so that the user interface can remain responsive and can show the secondary thread's progress. In this section, we will look at the Page Indexer application, shown in Figure 19.1, which indexes HTML files in a specified directory and all its subdirectories. The indexing work is passed off to a secondary thread that communicates with the primary thread to notify it of the progress that has been...

Model View Programming

Model view programming is a technique that involves separating data from its visual representation. It was first popularized as the MVC model view controller paradigm used in the Smalltalk programming language. A model is a class that provides a uniform interface through which data items can be accessed. A view is a class that can present the data items from a model to the user on-screen. A controller is a class that mediates between the user interface e.g., mouse events and key presses to...

The Event Handling Mechanism

PyQt provides two mechanisms for dealing with events the high-level signals and slots mechanism, and low-level event handlers. The signals and slots approach is ideal when we are concerned with what actions the user wants to perform, without getting bogged down in the details of how specifically they asked. Signals and slots can also be used to customize some aspects of how widgets behave. But when we need to go deeper, particularly when creating custom widgets, we need to use low-level event...

Online Help

There are three common ways to provide an online help system. One approach is to provide the help in the form of HTML files, and to launch a Web browser set to the relevant page. Another is to use the Qt Assistant application provided with Qt. The third approach is to provide a help form, again using HTML, but with the images and HTML files as resources. Figure 17.1 The Image Changer Help form Figure 17.1 The Image Changer Help form The first approach can be achieved by launching a Web browser...

Using QSyntax Highlighter

Text Editor Pyqt

If we want a Python-savvy text editor with syntax highlighting, we need not create one ourselves. The Tkinter-based IDLE application provides both a sandbox in which we can experiment with Python code, and a perfectly good Python code editor. And for more power, we can use Eric4, itself written in PyQt and using QScintilla for its text editing. However, no off-the-shelf editor will necessarily work in just the way we want, and since creating our own is instructive and revealing of what is...

Executing SQL Queries

Now that we have a connection, we can execute some SQL statements. query QSqlQuery query.exec_ CREATE TABLE outcomes id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL, name VARCHAR 40 NOT NULL query.execj CREATE TABLE calls id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL, FOREIGN KEY outcomeid REFERENCES outcomes We have not specified a particular database connection to use, so PyQt will use the default unnamed connection that we established earlier. The tables created by the SQL calls...

Creating Custom Models

In this section, we will create a custom model to hold the ship data, and display the same model in two different table views. An application that makes use of the model is shown in Figure 14.3. The user can scroll the tables independently, and can edit the data in either of them, safe in the knowledge that any changes will be automatically reflected in both views. We will begin by showing extracts from the application's main form. This will show us some of the model view API in use. Then we...

Dumb Dialogs

We define a dumb dialog to be a dialog whose widgets are set to their initial values by the dialog's caller, and whose final values are obtained directly from the widgets, again by the dialog's caller. A dumb dialog has no knowledge of what data its widgets are used to present and edit. We can apply some basic validation to a dumb dialog's widgets, but it is not common or always possible to set up validation that incorporates interdependencies between widgets in other words, form-level...

Smart Dialogs

We define a smart dialog to be one that initializes its widgets in accordance with data references or data structures that are passed to its initializer, and which is capable of updating the data directly in response to user interaction. Smart dialogs can have both widget-level and form-level validation. Smart dialogs are usually modeless, with apply and close buttons, although they can also be live, in which case they may have no buttons, with changes to widgets reflected directly into the...

Internationalization

Pyqt List Grid

There are several issues to consider when making applications suitable for users who speak a language that is different from the one used originally. The largest and most obvious issue is that all user-visible strings must be translated into the target language this includes not only the strings used for menu options and dialog buttons, but also tooltips, status tips, and any other online help. In addition, we must perform other localizations, such as making sure that numbers use the...

Item Based Graphics

If we create a custom widget and reimplement its paint event, we can draw any graphics we like. This approach was shown in the preceding chapter, and it is ideal for drawing custom widgets, for drawing graphs, and for drawing small numbers of items. But if we need to draw lots of independent items, anything from dozens to tens of thousands of them, or if we need to draw items that the user can interact with individually for example, clicking, dragging, and selecting them or if we need to...

Standard Dialogs

We consider a dialog to be a standard dialog if it initializes its widgets in accordance with the values set through its initializer or through its methods, and whose final values are obtained by method calls or from instance variables not directly from the dialog's widgets. A standard dialog can have both widget-level and form-level validation. Standard dialogs are either modal, with accept and reject buttons, or less commonly modeless, in which case they have apply and close buttons and...

Using Qt Designer

Pyqt Designer

In Chapter 5 we created dialogs purely by writing code. In our initializers we created the widgets we needed and set their initial properties. Then we created one or more layout managers to which we added the widgets to get the appearance we wanted. In some cases, when working with vertical or horizontal layouts we added a stretch which would expand to fill unwanted space. And after laying out the widgets we connected the signals we were interested in to the methods we wanted to handle them....