Skip to main content

PyQt By Example (Session 4)

PyQt By Example: Session 4



If you have not done it yet, please check the previous sessions:

All files for this session are here: Session 4 at GitHub. You can use them, or you can follow these instructions starting with the files from Session 3 and see how well you worked!


What's an Action?

When we finished session 3 we had a basic todo application, with very limited functionality: you can mark tasks as done, but you can't edit them, you can't create new ones, and you can't remove them, much less do things like filtering them.


A very limited application

Today we will start writing code and designing UI to do those things.

The key concept here is Actions.

  • Help? That's an action

  • Open File? That's an action

  • Cut / Copy / Paste? Those are actions too.

Let's quote The Fine Manual:

The QAction class provides an abstract user interface action that can be inserted into widgets.

In applications many common commands can be invoked via menus, tool bar buttons, and keyboard shortcuts. Since the user expects each command to be performed in the same way, regardless of the user interface used, it is useful to represent each command as an action.

Actions can be added to menus and tool bars, and will automatically keep them in sync. For example, in a word processor, if the user presses a Bold tool bar button, the Bold menu item will automatically be checked.

A QAction may contain an icon, menu text, a shortcut, status text, "What's This?" text, and a tooltip.

The beauty of actions is that you don't have to code things twice. Why add a "Copy" button to a tool bar, then a "Copy" menu entry, then write two handlers?

Create actions for everything the user can do then plug them in your UI in the right places. If you put them in a menu, it's a menu entry. If you put it in a tool bar, it's a button. Then write a handler for the action, connect it to the right signal, and you are done.

Let's start with a simple action: Remove Task. We will be doing the first half of the job, creating the action itself and the UI, using designer.

Creating Actions in Designer

First, let's go to the Action Editor and obviously click on the "New Action" button and start creating it:


Creating a New Action

A few remarks:

  • If you don't know where the "X" icon came from, you have not read session 3 ;-)

  • The actionDelete_Task object name is automatically generated from the text field. In some cases that can lead to awful names. If that's the case, you can just change the object name.

  • The same text is used for the iconText and toolTip properties. If that's not correct, you can change it later.

Once you create the action, it will not be marked as "Used" in the action editor. That's because it exists, but has not been made available to the user anywhere in the window we are creating.

There are two obvious places for this action: a tool bar, and a menu bar.

Adding Actions to a Tool Bar

To add an action to a tool bar, first make sure there is one. If you don't have one in your "Object Inspector", then right click on MainWindow (either the actual window, or its entry in the inspector), and choose "Add Tool Bar".

You can add as many tool bars as you want, but try to want only one, unless you have a very good reason (we will have one in session 5 ;-)

After you create the tool bar, you will see empty space between the menu bar (that says "Type Here") and the task list widget. That space is the tool bar.

Drag your action's icon from the action editor to the tool bar.

That's it!


The Delete Task action is now in the tool bar.

Adding Actions to a Menu Bar

Again, our menu bar is empty, it has only a sign saying "Type Here". While we could just drag our action to the menu bar, that would place "Delete Task" as a top level menu, which is really an unusual choice.

So, let's create a "Task" menu first:

  • Click on the "Type Here".

  • Type "Task" (without the quotes)


Creating a menu

If you see the last image, by doing that we created a QMenu object called menuTask (again, the object name is based on what we typed).

We want to add the delete task action to that menu. To do that, drag the action to the "Task" in the menu bar, then to the menu that appears when you do that.


The Delete Task action is now in the menu bar

Now we have our action in the tool bar and in the menu bar. But of course, it does nothing. So, let's work on that next.

Save it, run, let's move forward.

Deleting a Task

From session 2 you should remember AutoConnect. If you don't, refresh that session, because that's what we will use now. We want to do something when the actionDelete_Task object emits its triggered signal.

Therefore, we want to implement Main.on_actionDelete_Task_triggered (see why action's object names are important? I could have called it delete instead).

An Important Issue

Here we take a small detour because there is a problem with PyQt which is mildly annoying.

Consider this trivial version of our method:

def on_actionDelete_Task_triggered(self,checked=None):
    print "adtt",checked

What's printed if I click on the toolbar button?

[[email protected] session4]$ python
adtt False
adtt None

The same thing happens if you select "Delete Task" from the menu: our slot gets called twice. This problem is there when you use AutoConnect for signals with arguments that can also be emitted without arguments.

How can you tell if that's the case? In the Qt docs they will be listed with default arguments.

For example, this signal has the problem:

void triggered ( bool checked = false )

This one doesn't:

void toggled ( bool checked )

The technical explanation for this is ... involved but the practical solution is trivial:

Make sure checked is not None in your slot:

def on_actionDelete_Task_triggered(self,checked=None):
    if checked is None: return

This way, you will ignore the slot called with no arguments, and run the real code only once.

And here is the real code, which is quite short:

def on_actionDelete_Task_triggered(self,checked=None):
    if checked is None: return
    # First see what task is "current".

    if not item: # None selected, so we don't know what to delete!
    # Actually delete the task

    # And remove the item. I think that's not pretty. Is it the only way?

Except for the last line, that code should be obvious. The last line? I am not really sure it's even right but it works.

You can now test the feature. Remember that if you run out of tasks, you can execute python and get new ones.

Fine Tuning Your Actions

There are some interface problems with our work so far:

  1. The Task menu and the Delete Task action lack keyboard shortcuts.

    This is very important. It makes the app work better for the regular user. Besides, often they will expect the shortcuts to be there and there is no reason to frustrate your user!

    Luckily, this is trivial to fix, just set the shortcut property for action_Delete_Task, and change menuTask's text property to "&Task".

  2. The Delete Task action is enabled even when it doesn't apply. If you have no task selected, the user can trigger it, but it does nothing. That's a bit surprising, and surprising your users is not very nice, IMHO.

    There is some argument about this, notably from Joel Spolsky so maybe I am just old fashioned!

    To selectively enable or disable your actions when there is/isn't a selected item in our task list, we need to react to our list's currentItemChanged signal. Here's the code:

    def on_list_currentItemChanged(self,current=None,previous=None):
        if current:

    Also, we need to make Delete Task start disabled because we start the app with no task selected. That's done from designer using its "enabled" property.

    Since there is only one Delete Task action, this code affects the task bar and also the menu bar. That helps keep your UI consistent and well-behaved.


A very limited application

Coming Soon

Well, that was a rather long explanation for a small feature, wasn't it? Don't worry, the next actions will be much easier to add, because I expect you to read "I added an action called New Task" and know what I am talking about.

And in the next session, we will do just that. And we will create our first dialog.

Further Reading

Here you can see what changed between the old and new versions:

Modified lines:  None
Added line:  44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62
Removed line:  None
Generated by diff2html
© Yves Bailly, MandrakeSoft S.A. 2001
diff2html is licensed under the GNU GPL.

  session3/     session4/
  60 lines
1557 bytes
Last modified : Thu Mar 5 02:03:34 2009

    79 lines
2300 bytes
Last modified : Sat Mar 7 02:06:29 2009

1 # -*- coding: utf-8 -*-   1 # -*- coding: utf-8 -*-
2   2
3 """The user interface for our app"""   3 """The user interface for our app"""
4   4
5 import os,sys   5 import os,sys
6   6
7 # Import Qt modules   7 # Import Qt modules
8 from PyQt4 import QtCore,QtGui   8 from PyQt4 import QtCore,QtGui
9   9
10 # Import the compiled UI module   10 # Import the compiled UI module
11 from windowUi import Ui_MainWindow   11 from windowUi import Ui_MainWindow
12   12
13 # Import our backend   13 # Import our backend
14 import todo   14 import todo
15   15
16 # Create a class for our main window   16 # Create a class for our main window
17 class Main(QtGui.QMainWindow):   17 class Main(QtGui.QMainWindow):
18     def __init__(self):   18     def __init__(self):
19         QtGui.QMainWindow.__init__(self)   19         QtGui.QMainWindow.__init__(self)
20   20
21         # This is always the same   21         # This is always the same
22         self.ui=Ui_MainWindow()   22         self.ui=Ui_MainWindow()
23         self.ui.setupUi(self)   23         self.ui.setupUi(self)
24   24
25         # Let's do something interesting: load the database contents   25         # Let's do something interesting: load the database contents
26         # into our task list widget   26         # into our task list widget
27         for task in todo.Task.query().all():   27         for task in todo.Task.query().all():
28             tags=','.join([ for t in task.tags])   28             tags=','.join([ for t in task.tags])
29             item=QtGui.QTreeWidgetItem([task.text,str(,tags])   29             item=QtGui.QTreeWidgetItem([task.text,str(,tags])
30             item.task=task   30             item.task=task
31             if task.done:   31             if task.done:
32                 item.setCheckState(0,QtCore.Qt.Checked)   32                 item.setCheckState(0,QtCore.Qt.Checked)
33             else:   33             else:
34                 item.setCheckState(0,QtCore.Qt.Unchecked)   34                 item.setCheckState(0,QtCore.Qt.Unchecked)
35             self.ui.list.addTopLevelItem(item)   35             self.ui.list.addTopLevelItem(item)
36   36
37     def on_list_itemChanged(self,item,column):   37     def on_list_itemChanged(self,item,column):
38         if item.checkState(0):   38         if item.checkState(0):
39             item.task.done=True   39             item.task.done=True
40         else:   40         else:
41             item.task.done=False   41             item.task.done=False
42         todo.saveData()   42         todo.saveData()
43   43
      44     def on_actionDelete_Task_triggered(self,checked=None):
      45         if checked is None: return
      46         # First see what task is "current".
      47         item=self.ui.list.currentItem()
      49         if not item: # None selected, so we don't know what to delete!
      50             return
      51         # Actually delete the task
      52         item.task.delete()
      53         todo.saveData()
      55         # And remove the item. I think that's not pretty. Is it the only way?
      56         self.ui.list.takeTopLevelItem(self.ui.list.indexOfTopLevelItem(item))
      58     def on_list_currentItemChanged(self,current=None,previous=None):
      59         if current:
      60             self.ui.actionDelete_Task.setEnabled(True)
      61         else:
      62             self.ui.actionDelete_Task.setEnabled(False)
44   63
45 def main():   64 def main():
46     # Init the database before doing anything else   65     # Init the database before doing anything else
47     todo.initDB()   66     todo.initDB()
48   67
49     # Again, this is boilerplate, it's going to be the same on   68     # Again, this is boilerplate, it's going to be the same on
50     # almost every app you write   69     # almost every app you write
51     app = QtGui.QApplication(sys.argv)   70     app = QtGui.QApplication(sys.argv)
52     window=Main()   71     window=Main()
53   72
54     # It's exec_ because exec is a reserved word in Python   73     # It's exec_ because exec is a reserved word in Python
55     sys.exit(app.exec_())   74     sys.exit(app.exec_())
56   75
57   76
58 if __name__ == "__main__":   77 if __name__ == "__main__":
59     main()   78     main()
60   79

Generated by diff2html on Sat Mar 7 02:08:22 2009
/home/ralsina/bin/diff2html session3/ session4/