You are here: Home > Python > Introduction to PyQT4

Introduction to PyQT4

 
Creating an application in PyQT4 may be done in a few ways. The most common one is to use QTDesigner, which we get with QT. QTDesigner let us draw the GUI which is very handy for complicated interfaces. We can place widgets on the window, add names etc. To create an application in PyQT4 you have to:

Tutorials List

  • Simple text editor in PyQT4 - First application in PyQT4
  • Extending PyQT4 text editor - Adding more features using PyQT4 widgets
  • QYolk I - List widgets in PyQt4 - How to use list widgets in PyQt4
  • QYolk II - Containers - How to use a Tab Widget
  • PyQT4 Text editor - final changes - Some advanced PyQT4 features
  • QYolk III - List of updates - A new feature
  • QScintilla2 and PyQT4 - Adding widgets for programmers to PyQt4.
  • More soon...

    Introduction

    We start with a "Hello... Close Button". When you launch the QTDesigner you will be able to chose base window type:
    pyqt4_1.png
    We choose simple Widget, which will give us a simple window. From the right menu we drag one Push Button on to the window:
    pyqt4_2.png
    Right-Click on the pushButton will allow us to change its caption (displayed text).
    pyqt4_3.png
    When the GUI is done we can use QTDesigner to connect widgets with "simple" predefined slots - in our case we want the "close()" slot which will close the application. To do that we have to switch to Signal Editing:
    pyqt4_6.png
    To connect a widget with a signal press the mouse button over the pushButton and move the mouse pointer over the wiget window and then drop:
    pyqt4_5.png
    A Signal-Slots window should appear:
    pyqt4_4.png
    The signal is clicked() and slot is close. Now we save the gui as for example test.ui. In the terminal go to the folder with saved GUI (ui file) and type:
    pyuic4 test.ui > test_ui.py
    Next create test.py file with the code:
    import sys
    from PyQt4 import QtCore, QtGui
    
    from test_ui import Ui_Form
    
    
    class MyForm(QtGui.QMainWindow):
        def __init__(self, parent=None):
            QtGui.QWidget.__init__(self, parent)
            self.ui = Ui_Form()
            self.ui.setupUi(self)
    
    
    if __name__ == "__main__":
        app = QtGui.QApplication(sys.argv)
        myapp = MyForm()
        myapp.show()
        sys.exit(app.exec_())
    
    And run it:
    python test.py
    You will see our application, and when you click the button it will close.

    Notes

    Ui_Form is the class name generated by pyuic4 the "Form" part is the name of the main window. You can change it in QTDesigner (we will do this in next tutorial). You have to change the objectName:
    pyqt4_7.png
    The code from test.py is a general code for running and extending GUI classes generated by pyuic4.
    Hosting NRC-FOSS at AU-KBC.. Django/Python powered.