April 23, 2014
 
 
RSSRSS feed

Make Pretty GUI Apps Fast with Python-Qt

A Minimal Window, Signals and Slots

  • January 28, 2010
  • By Akkana Peck

KDE users love the look of all those pretty applications. The key is the toolkit KDE uses: Qt.

Qt's Python bindings -- called Python-Qt -- make it easy to build up a good-looking application quickly. The best way to get Python-Qt is via your distro: for instance, on Ubuntu, look for the package called python-qt4. To install from source, follow the links at Installing PyQt. You'll need to install sip first, if your distro doesn't already provide it.

A minimal window

Let's start with a very minimal window, with just a quit button.

You'll need to import two PyQt modules: PyQt4.QtCore and PyQt4.QtCore. It's not always obvious which module will contain a particular object. So if you want to be able to copy other people's code, it's easiest to import everything from both those modules. You'll also need the sys module so you can access command-line arguments with sys.argv.

#! /usr/bin/python

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys

Qt has a class called QMainWindow that makes it easy to combine a menubar, a toolbar, your application content (called the "central widget"), and a status bar at the bottom. For now, I'll only use the central widget.

class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        # The only thing in the app is a quit button
        quitbutton = QPushButton('Close', self)
        self.setCentralWidget(quitbutton)

Create a QApplication and an instance of your main window:

app = QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())

Now run the application:

python button.py

and you'll see a window like Figure 1.

figure 1
figure 1

 

Signals and slots

But wait -- the button doesn't do anything yet! You want a click on the button to quit the application. To do that, add another line inside MainWindow's __init__ function, just after you create the quitbutton:

        self.connect(quitbutton, SIGNAL('clicked()'), SLOT('close()'))

What's all that SIGNAL and SLOT stuff?

Just the way Qt connects widgets to actions. The Qt project makes much of their "Signals and Slots" design. But if you've done GUI programming in any other toolkit, Qt is really no different. Each Qt widget has a list of signals it can send -- for instance, a QPushButton can be "clicked". You can also define callback functions to be called when a signal occurs: Qt calls these slots. QtCore.SIGNAL and QtCore.SLOT take the name of a signal or slot and turn it into a real function you can pass to connect.

Or you can skip using SLOT entirely and just pass a function name, without trailing parentheses:

        self.connect(quitbutton, SIGNAL('clicked()'), self.close)

 

Sitemap | Contact Us