DEV Community

Michael Herrmann
Michael Herrmann

Posted on

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:

python -m venv virtualenv
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

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
Enter fullscreen mode Exit fullscreen mode

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:

Qt sample application

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

QTextEdit screenshot

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

QTextEdit sample code on Windows

The first line tells Python to load PySide:

from PySide2.QtWidgets import *
Enter fullscreen mode Exit fullscreen mode

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([])
Enter fullscreen mode Exit fullscreen mode

Then, we create the text area via the line:

text_area = QTextEdit()
Enter fullscreen mode Exit fullscreen mode

We tell Qt to display the text area:

text_area.show()
Enter fullscreen mode Exit fullscreen mode

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

app.exec_()
Enter fullscreen mode Exit fullscreen mode

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

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_()
Enter fullscreen mode Exit fullscreen mode

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

It for instance shows:

(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:

pip install requests
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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'})
Enter fullscreen mode Exit fullscreen mode

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_()
Enter fullscreen mode Exit fullscreen mode

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

QTimer example

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
Enter fullscreen mode Exit fullscreen mode

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_()
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

To start a new fbs project, enter:

python -m fbs startproject
Enter fullscreen mode Exit fullscreen mode

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 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
Enter fullscreen mode Exit fullscreen mode

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

python -m fbs freeze
Enter fullscreen mode Exit fullscreen mode

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 to be on the PATH. On Linux, you need fpm.)

If you have an existing application that you wish to convert to fbs, this article 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.

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.

Top comments (1)

Collapse
 
taranakiretreat profile image
Jamie Allen

Hi there - this is precisely what I need for an application I'm building - THANK YOU!
I'm curious about the server, and wondered if I could ask you a couple of questions about that, please as soon as poss? I really look forward to hearing from you... With grateful thanks again, Jamie