English French [qt-devnet.developpez.com] Japanese

Combine – Licence, About and Close

In this script we shall combine the three previous mini-scripts to one mini-program, which we name combine. All the required material, including listing of sources, is available for download in tuts4pyside. All current source code for “Close”, “About”, “Show Licence”, all versions of “Combined”, “Engineering Application” aka “truss” are stored in one repository tuts4pyside. For your convenience, please install a copy of the repository with the following command:

  1.   git  clone  https://github.com/OldAl/tuts4pyside

If you do not have git, pllease install it first. The first task is to use Qt Designer to design a form and save it in a combine.ui file. This time, we add to the menu bar a File item with sub-tems Show CCPL, About and Close. Qt Designer has a Signal/Slot Editor connecting tool. There we select from the drop-down menus Sender: action_Close, Signal: triggered, Receiver: MainWindow and Slot: close().

In Qt parlance, various clicks or other actions cause signals which need to be connected to the action we want to associate with the signal. The location where the signal is received is called slot. For GUI design, we usually use the provided standard signals. One such fairly general signal is triggered.

The signals are connected to slots and with PySide it can be any Python method, though in our example it is a reaction to it by the MainWindow, which closes, thus terminating the program.

The form is saved as combine.ui. This needs to be converted to the Python readable format as follows:

  1. pyside-uic combine.ui > ui_combine.py

The ui_combine.py can be read by Python and is reasonably understandable for us, humans as well. It is instructive to see this program in action, so we give its listing.

  1. #!/usr/bin/env python
  2. # combine.py - combination of ShowGPL, About, Close scripts
  3.  
  4. import sys
  5. import platform
  6.  
  7. import PySide
  8. from PySide.QtGui import QApplication, QMainWindow, QTextEdit,\
  9.                          QPushButton,  QMessageBox
  10.  
  11. __version__ = '0.0.1'
  12.  
  13. from ui_combine import Ui_MainWindow
  14.  
  15. class MainWindow(QMainWindow, Ui_MainWindow):
  16.     def __init__(self, parent=None):
  17.         super(MainWindow, self).__init__(parent)
  18.         self.setupUi(self)
  19.        
  20. if __name__ == '__main__':
  21.     app = QApplication(sys.argv)
  22.     frame = MainWindow()
  23.     frame.show()
  24.     app.exec_()

The code of this program is about 15 lines only and most are a kind of standard, which we will reuse again and again. It is useful and instructive to run this ‘‘program’‘ and make sure that it looks OK. We can test triggering all menu items, but only one, namely Close item is functional. For all others we need to provide appropriate code and that is our next step:

  1. #!/usr/bin/env python
  2. # combine.py - combination of ShowGPL, About, Close scripts
  3. # Copyright note omitted.
  4.  
  5. import sys
  6. import platform
  7.  
  8. import PySide
  9. from PySide.QtGui import QApplication, QMainWindow, QTextEdit,\
  10.                          QPushButton,  QMessageBox
  11.  
  12. __version__ = '0.0.2'
  13. from ui_combine import Ui_MainWindow
  14.  
  15. class MainWindow(QMainWindow, Ui_MainWindow):
  16.     def __init__(self, parent=None):
  17.         super(MainWindow, self).__init__(parent)
  18.         self.setupUi(self)
  19.         self.actionShow_GPL.triggered.connect(self.showGPL)
  20.         self.action_About.triggered.connect(self.about)        
  21.                
  22.     def showGPL(self):
  23.         '''Read and display GPL licence.'''
  24.         self.textEdit.setText(open('COPYING.txt').read())
  25.        
  26.     def about(self):
  27.         '''Popup a box with about message.'''
  28.         QMessageBox.about(self, "About PyQt, Platform and the like",
  29.                 """<b> About this program </b> v %s
  30.                <p>Copyright 2010 Joe Bloggs.
  31.                All rights reserved in accordance with
  32.                GPL v2 or later - NO WARRANTIES!
  33.                <p>This application can be used for
  34.                displaying OS and platform details.
  35.                <p>Python %s -  PySide version %s - Qt version %s on %s""" % \
  36.                 (__version__, platform.python_version(), PySide.__version__,\
  37.                  PySide.QtCore.__version__, platform.system()))      
  38.        
  39. if __name__ == '__main__':
  40.     app = QApplication(sys.argv)
  41.     frame = MainWindow()
  42.     frame.show()
  43.     app.exec_()

We simply added the methods ‘’‘about’‘’ and ‘’‘showGPL’‘’ and connected them to the signals with the two statements:
  1.         self.actionShow_GPL.triggered.connect(self.showGPL)
  2.         self.action_About.triggered.connect(self.about)        

Our program is now fully functional and we could congratulate ourselves and move to some other task. But our GUI does not look great, because most GUIs have alternative ways to achieve the tasks of menu items, buttons or tool bar with icons that cause the appropriate action. Also when the mouse pointer moves over one of the icons it is nice to show a hint of what the icon stands for and also show a message on the task bar that the MainWindow provides by default at the bottom of the form.

Our next task is to provide those facilities.

In this part of the tutorial, we will tackle the method to provide tool bar with enabled icons as well as tip point and status bar hints. First we need some icons. We do not believe in reinventing the wheel, so let us use some readily available set of icons. Our choice is a free “tango icon set” from http://tango.freedesktop.org/Tango_Icon_Library
It is a fairly large collection of icons that the its authors have put out free of any licence restrictions. It should more than cover our requirements. It is convenient to put the selected icons in a small library which we call tango_select. Analogous to combine.ui file from Qt Designer, with a plain text editor (Notepad in windows, kate in KDE, gedit in Gnome) we make up a resource source file combine.qrc. Though it is “black magic XML” it has a simple format that can be copied and modified with ease. Let us look at the listing of it:

  1. <!DOCTYPE RCC><RCC version="1.0">
  2. <file alias="quit.png">select_tango/32x32/actions/system-log-out.png</file>
  3. <file alias="about.png">select_tango/32x32/apps/preferences-system-session.png</file>
  4. <file alias="showgpl.png">select_tango/32x32/apps/help-browser.png</file>
  5. </RCC>

For example, the icon for quit action will be referred to in the program by its alias quit.png. This will use from tango collection system-log-out.png icon. (We hope you have downloaded the free source of tango. If so, you should substitute tango for “select_tango” in the “magic” file *combine.qrc. Now, similarly to combine.ui, we compile the file to ui_combine.py as follows:

  1.   pyside-rcc combine.qrc -o qrc_combine.py

  • Note: pyside-rcc generates code for Python v2.x by default. If you’re developing with Python v3.x, make sure to use the option -py3 or you will get errors.
    1.   pyside-rcc -py3 combine.qrc -o qrc_combine.py

The qrc_combine.py file is simply imported in to the program as shown in the listing.

  1. #!/usr/bin/env python
  2. # combine.py - combination of ShowGPL, About, Close scripts
  3.  
  4. # Copyright notice removed to save space.
  5.  
  6. import sys
  7. import platform
  8.  
  9. import PySide
  10.                          QMessageBox,  QIcon
  11.  
  12. __version__ = '0.0.3'
  13. from ui_combine import Ui_MainWindow
  14. import qrc_combine
  15.  
  16. class MainWindow(QMainWindow, Ui_MainWindow):
  17.     def __init__(self, parent=None):
  18.         super(MainWindow, self).__init__(parent)
  19.         self.setupUi(self)
  20.         self.actionShow_GPL.triggered.connect(self.showGPL)
  21.         self.action_About.triggered.connect(self.about)        
  22.         iconToolBar = self.addToolBar("iconBar.png")
  23. #------------------------------------------------------
  24. # Add icons to appear in tool bar - step 1
  25.         self.actionShow_GPL.setIcon(QIcon(":/showgpl.png"))
  26.         self.action_About.setIcon(QIcon(":/about.png"))
  27.         self.action_Close.setIcon(QIcon(":/quit.png"))
  28. #------------------------------------------------------
  29. # Show a tip on the Status Bar - step 2
  30.         self.actionShow_GPL.setStatusTip("Show GPL Licence")
  31.         self.action_About.setStatusTip("Pop up the About dialog.")
  32.         self.action_Close.setStatusTip("Close the program.")
  33. #------------------------------------------------------        
  34.         iconToolBar.addAction(self.actionShow_GPL)
  35.         iconToolBar.addAction(self.action_About)
  36.         iconToolBar.addAction(self.action_Close)
  37.        
  38.     def showGPL(self):
  39.         '''Read and display GPL licence.'''
  40.         self.textEdit.setText(open('COPYING.txt').read())
  41.        
  42.     def about(self):
  43.         '''Popup a box with about message.'''
  44.         QMessageBox.about(self, "About PyQt, Platform and the like",
  45.                 """<b> About this program </b> v %s
  46.                <p>Copyright 2010 Joe Bloggs.
  47.                All rights reserved in accordance with
  48.                GPL v2 or later - NO WARRANTIES!
  49.                <p>This application can be used for
  50.                displaying OS and platform details.
  51.                <p>Python %s -  PySide version %s - Qt version %s on %s""" % \
  52.                 (__version__, platform.python_version(), PySide.__version__,\
  53.                  PySide.QtCore.__version__, platform.system()))      
  54.        
  55. if __name__ == '__main__':
  56.     app = QApplication(sys.argv)
  57.     frame = MainWindow()
  58.     frame.show()
  59.     app.exec_()

Icon images are added to the actions in the program part, marked as step 1

  1. #------------------------------------------------------
  2. # Add icons to appear in tool bar - step 1
  3.         self.actionShow_GPL.setIcon(QIcon(":/showgpl.png"))
  4.         self.action_About.setIcon(QIcon(":/about.png"))
  5.         self.action_Close.setIcon(QIcon(":/quit.png"))
  6. #------------------------------------------------------

Similarly, the hint texts are added to the program in step 2:
  1. #------------------------------------------------------
  2. # Show a tip on the Status Bar - step 2
  3.         self.actionShow_GPL.setStatusTip("Show GPL Licence")
  4.         self.action_About.setStatusTip("Pop up the About dialog.")
  5.         self.action_Close.setStatusTip("Close the program.")
  6. #------------------------------------------------------

“One image is worth a thousand words”, according to an old proverb of an old culture. The finished combine.py shows the gui, stored in an external repository:

A hint: to remove, simply comment the lines by adding “hash” character in column 1 and remove the hash later as required.

Main requirement: enjoy!

Heard in a tutorial class: A lecturer explained to a complaining mother of a first year student: Your son simply is not intelligent enough to complete this course. I explained to him PySide once; I explained to him a second time;
I explained it all in even greater detail the third time. Even I understood PySide then, but your son still did not understand it!

I hope even I now understand better how to program GUI in Pyside :)

Return to PySideSimplicissimus

Categories: