Python Qt tutorial: Create a simple chat client
Tags: python, qt
Published: 2018-11-14 11:10:48

---
title: Python Qt tutorial: Create a simple chat client
published: true
description: This Python Qt tutorial shows you how to create a (working!) chat client for Windows, Mac or Linux. We will install Qt for Python, write the client and build an installer for it. 
tags: python,qt
---

This Python Qt tutorial shows you how to create a (working!) chat client for Windows, Mac or Linux. We will install Qt for Python, write the client and build an installer for it.

# Using Qt from Python

[Qt](https://www.qt.io/) is a GUI framework. It is developed in C++. But in 2018, the Qt company released [Qt for Python](https://www.qt.io/qt-for-python). This gives you the increased productivity of this dynamic language, while retaining most of the speed of C++.

Before Qt for Python came out, most people used a library called [PyQt](https://riverbankcomputing.com/software/pyqt/intro). It is more mature, and very stable. Its drawback is that it requires you to purchase a license for commercial projects. This is unlike Qt for Python, which is licensed under the LGPL and can thus normally be used for free.

From a code perspective, it does not make much of a difference which of the two bindings you use. Their APIs are almost exactly the same. We use Qt for Python here because it is newer. If you want to use PyQt instead, check out [this PyQt5 tutorial](https://build-system.fman.io/pyqt5-tutorial).

# Installing Qt for Python

Installing Qt in Python 3 is very easy, thanks to the venv and pip modules. Open a terminal and navigate to an empty directory. Assuming Python's installation directory is on your PATH, you can then enter the following:

    python -m venv virtualenv

This creates a virtual environment in the `virtualenv` directory. It will store your project's dependencies.

To activate the virtual environment, use one of the following two commands:

    call virtualenv\scripts\activate.bat  # on Windows
    source virtualenv/bin/activate        # On Mac / Linux

You can tell that the activation was successful by the `(virtualenv)` prefix in your shell:

![Screenshot of an activate Python 3 virtual environment on Windows](https://build-system.fman.io/static/public/img/python3-virtual-environment-active-screenshot-windows.png)

For the remainder of this tutorial, we will assume that the virtual environment is active.

To install Qt for Python, enter the following command:

    pip install PySide2

It's called `PySide2` for historical reasons: PySide were the first official Python bindings, released in 2009 by then-owner of Qt Nokia. After Nokia sold Qt in 2011, development of PySide stalled. PySide2 was a community effort to maintain it. Finally, in 2016, the Qt company [committed](https://groups.google.com/d/msg/pyside-dev/pqwzngAGLWE/kXUpXBhILAAJ) to officially supporting this project.

# A chat client

We will now use Qt for Python to create a (working!) chat client. Here is what it looks like:

![Qt sample application](https://build-system.fman.io/static/public/img/python-qt-tutorial/qt-example-application.png)

We'll build this top to bottom. First, the text area that displays everybody's messages:

![QTextEdit screenshot](https://build-system.fman.io/static/public/img/python-qt-tutorial/qtextedit-screenshot.png)

To display it, start `python` in your terminal and enter the following commands:

![QTextEdit sample code on Windows](https://build-system.fman.io/static/public/img/python-qt-tutorial/qtextedit-sample-code.png)

The first line tells Python to load PySide:

    from PySide2.QtWidgets import *

Next, we create a `QApplication`. This is required in any Qt application. We pass the empty brackets `[]` to indicate that there are no command line parameters:

    app = QApplication([])

Then, we create the text area via the line:

    text_area = QTextEdit()

We tell Qt to display the text area:

    text_area.show()

This opens a window. To make it respond to user input, we finally need the following command:

    app.exec_()

Now Qt processes key strokes, mouse events etc. until you close the little window that contains the text field.

If the above worked as in the screenshot then congratulations! You just created a very simple GUI application with Qt for Python.

# Positioning GUI elements

We now want to add the text field for entering messages below the text area:

![Qt sample application: A QLineEdit below a QTextEdit](https://build-system.fman.io/static/public/img/python-qt-tutorial/qt-example-application-empty.png)

But how do we tell Qt to place it below (and not, say, to the right of) the text area? The answer is through a *layout*. Layouts tell Qt how to position GUI elements.

To put the text field below the text area, we use a `QVBoxLayout` as follows:

    from PySide2.QtWidgets import *
    app = QApplication([])
    layout = QVBoxLayout()
    layout.addWidget(QTextEdit())
    layout.addWidget(QLineEdit())
    window = QWidget()
    window.setLayout(layout)
    window.show()
    app.exec_()

We again import `PySide2` and create a `QApplication`. We proceed to build the layout: First a text area like the one we had before. Then a text field of type `QLineEdit`. Next, we create a window to contain our layout. We end by calling `.show()` on it and using `app.exec_()` to hand control over to Qt.

# Interlude: Widgets

`QWidget`, which we saw above, is the most basic GUI element in Qt. All other controls are specialisations of it: buttons, labels, windows, text fields, etc. Widgets are like HTML elements in that they encapsulate looks and behaviour, and can be nested.

Here is a screenshot of the most important Qt widgets:

![Screenshot of the most common Qt widgets](https://build-system.fman.io/static/public/img/python-qt-tutorial/qt-widgets-screenshot.png)

It for instance shows:

* [QLabel](https://doc.qt.io/qt-5/qlabel.html)
* [QComboBox](https://doc.qt.io/qt-5/qcombobox.html)
* [QCheckBox](https://doc.qt.io/qt-5/qcheckbox.html)
* [QPushButton](https://doc.qt.io/qt-5/qpushbutton.html)
* [QRadioButton](https://doc.qt.io/qt-5/qradiobutton.html)
* [QTextEdit](https://doc.qt.io/qt-5/qtextedit.html)
* [QLineEdit](https://doc.qt.io/qt-5/qlineedit.html)
* [QSlider](https://doc.qt.io/qt-5/qslider.html)
* [QProgressBar](https://doc.qt.io/qt-5/qprogressbar.html)

(The code for the screenshot is available [here](https://build-system.fman.io/static/public/files/widgets_example_pyside.py) for your reference.)

# Talking to the server

With the GUI ready, we need to connect it to a server. The easiest way to do this is via the `requests` library. You can install it via the command:

    pip install requests

Once you have done this, start python again and enter the following commands:

    import requests
    chat_url = 'https://build-system.fman.io/chat'
    requests.get(chat_url).text

This should give you the HTML of the last chat messages.

We can also send a message. Here is an example, but be sure to use your own name and text :-)

    requests.post(chat_url, {'name': 'Matt', 'message': 'Nice tutorial'})

When you then call `requests.get(chat_url).text` again, your message should be at the end of the output.

# Signals

Our chat client needs to handle certain events:

* When the user presses `Enter`, the current message should be sent to the server.
* Once per second, we want to fetch and display new messages from the server.

Qt uses a mechanism called *signals* for reacting to events such as user input or timers. Here is an example:

    from PySide2.QtWidgets import *
    from PySide2.QtCore import QTimer
    app = QApplication([])
    timer = QTimer()
    timer.timeout.connect(lambda: print('hi!'))
    timer.start(1000)
    app.exec_()

When you run this code, the message `hi!` appears in your terminal once per second:

![QTimer example](https://build-system.fman.io/static/public/img/python-qt-tutorial/qtimer-example.png)

The signal in the above code is `timer.timeout`. We used its `.connect(...)` method to specify a function that gets called when the signal occurs. In the example, we used the inline function `lambda: print('hi!')`. Our other call `timer.start(1000)` then ensured that Qt runs this function every 1,000 milliseconds.

# Putting it all together

We are now in a position to fully implement the chat client. Copy the below code into a file next to your `virtualenv` directory, say as `main.py`. Be sure to fill in your name at the top, or you won't be able to post messages. Then you can run the chat with the following command:

    python main.py

You'll be able to see what others have written and send messages of your own. Happy chatting! :-)

    from PySide2.QtCore import *
    from PySide2.QtWidgets import *
    
    import requests
    
    name = '' # Enter your name here!
    chat_url = 'https://build-system.fman.io/chat'
    
    # GUI:
    app = QApplication([])
    text_area = QTextEdit()
    text_area.setFocusPolicy(Qt.NoFocus)
    message = QLineEdit()
    layout = QVBoxLayout()
    layout.addWidget(text_area)
    layout.addWidget(message)
    window = QWidget()
    window.setLayout(layout)
    window.show()
    
    # Event handlers:
    def refresh_messages():
        text_area.setHtml(requests.get(chat_url).text)
    
    def send_message():
        requests.post(chat_url, {'name': name, 'message': message.text()})
        message.clear()
    
    # Signals:
    message.returnPressed.connect(send_message)
    timer = QTimer()
    timer.timeout.connect(refresh_messages)
    timer.start(1000)
    
    app.exec_()

# Running your app on other computers

We can now start our app with the command `python main.py`. But how do we run it on somebody else's computer? Especially if they don't have Python installed?

What we want is a standalone executable that does not require Python (or anything else) to run. The process of creating such a binary is called *freezing* in Python.

Special Python libraries such as PyInstaller let you freeze applications. Unfortunately, they only get you 80% of the way. Very often, you still have to manually add or remove DLLs or shared libraries. And they don't address basic tasks such as accessing data files, creating installers or automatic updates.

We will therefore use a more modern library called [fbs](https://build-system.fman.io). It is based on PyInstaller but adds the missing 20%. You can install it via the following command:

    pip install fbs PyInstaller==3.4

To start a new fbs project, enter:

    python -m fbs startproject

This asks you a few questions. You can use *Chat* as the application name and your name as the author.

Once you have done this, please [download this file](https://build-system.fman.io/static/public/files/python-qt-tutorial/main.py) and copy it over `src/main/python/main.py`. Open the file with a text editor and replace name by your name. The following command then starts the Chat as before:

    python -m fbs run

But what's more, you can now create a standalone executable via the command:

    python -m fbs freeze

This freezes your Python code to the folder target/Chat. You can copy this directory to any other computer with the same OS as yours to run the Chat there. Isn't that awesome?

# Creating an installer

You can also use fbs to generate an installer. This is done with the command `python -m fbs installer`:

(On Windows, this step requires [NSIS](http://nsis.sourceforge.net/Main_Page) to be on the PATH. On Linux, you need [fpm](https://fpm.readthedocs.io/en/latest/installing.html).)

If you have an existing application that you wish to convert to fbs, [this article](https://build-system.fman.io/pyqt-exe-creation/) may help you. It is written for PyQt, but is equally applicable to Qt for Python / PySide. Another good source of information is [fbs's tutorial](https://github.com/mherrmann/fbs-tutorial).

# Conclusion

We saw above how Qt for Python can be used to create a simple desktop application. We used basic widgets such as `QTextEdit` and `QLineEdit`, as well as `QVBoxLayout` to arrange them. Qt's signals let us make this GUI dynamic: First by using a timer to fetch the latest messages from the server every 1,000ms. And second by letting us respond to the user pressing the Enter button to submit a message. Finally, we used fbs to easily create a standalone executable and an installer.

Feel free to reach out to me on Twitter @m_herrmann if you have any questions or comments!

*This post was originally published [here](https://build-system.fman.io/python-qt-tutorial).*