Python Qt tutorial: Create a simple chat client
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 is a GUI framework. It is developed in C++. But in 2018, the Qt company released 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. 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.
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:
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: For the remainder of this tutorial, we will assume that the virtual environment is active. To install Qt for Python, enter the following command:
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 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: We’ll build this top to bottom. First, the text area that displays everybody’s messages:
To display it, start python in your terminal and enter the following commands:
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:
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: 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: It for instance shows:
- QLabel
- QComboBox
- QCheckBox
- QPushButton
- QRadioButton
- QTextEdit
- QLineEdit
- QSlider
- QProgressBar
(The code for the screenshot is available here 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:
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 🙂
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:
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:
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, ) 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. 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: