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...

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...

Static Data and Static Methods and Decorators

In some situations it is useful to have data that is associated with a class as a whole rather than with its instances. For example, if we have a Balloon class, we might want to know how many unique colors have been used self.color color Balloon.unique_colors.add color Static data is created inside a class block, but outside of any def statements. To access static data, we must qualify the name, and the easiest way to do so is by using the class name, as we do in the Balloon class's static...

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...

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 ,...

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...

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...

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...

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...

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...

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...

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,...

Designing User Interfaces

Tkinter Dialog Example

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...

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...

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...

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...

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...

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...

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...

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....

Rich Text and Printing

PyQt supports rich text, essentially a subset of HTML that also includes some support for CSS cascading style sheets . This means that in practice, we can pass strings that contain HTML markup to many of PyQt s text-handling classes and rely on PyQt to render the HTML properly in the user interface. We have already seen examples of passing HTML to QLabels. The graphicsitem class QGraphicsTextItem can also accept HTML. The QTextBrowser class supports basic HTML display including hyperlinks, and...