Getting started with PyQt

Saturday , 22, December 2012

I recently downloaded PyQt, which allows me to make GUI’s for my python scripts. I found this website to explain the ins and outs of PyQt. It had one page with some examples and slides dedicated to designing a GUI and implementing it in your python code. It however didn’t fully explain the details. After some fiddling around this is what I found if you want to make python code from your GUI design:

  1. Make a GUI using Qt Designer.
    1. If you want to include images you need to refer to them using a .QRC file. The PyQt examples have such a file. In Qt Designer you can add an image by right-clicking the object (such as a Frame) > Change styleSheet > Add Resource > Image > select the .QRC file in your file system > Select the image.
    2. Save the design as application.ui.
  2. After the installation of PyQt the pyuic4 utility is in the PATH so you can use it. This utility makes python code from the .UI file. Usage:> pyuic4 application.ui -x>application.pyw
  3. You now need to make the referenced images into python code:> pyrcc4 -py2 -o application.qrc
  4. Now run application.pyw.

In the examples folder of PyQt (<Your Python Folder>\Lib\site-packages\PyQt4\examples) there are numerous python script examples. In the pyuic folder compile-on-the-fly.pyw can be found which shows how to include a .UI file without having to compile using pyuic4.

This little python code example shows how to use a UI on the fly:

import sys,os

from PyQt4 import QtCore, QtGui, uic

form_class, base_class = uic.loadUiType('application.ui')

class MainWindow(QtGui.QMainWindow):
    MESSAGE = "Hello!"
    def __init__(self, parent = None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = form_class()
    def informationMessage(self):
        reply = QtGui.QMessageBox.information(self,
                "QMessageBox.information()", MainWindow.MESSAGE)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = MainWindow()

The needed application.ui is just a simple GUI with a button named ‘pushButton’, made in Qt Designer.

Please give us your valuable comment