In this part of the PyQt5 tutorial we learn some basic functionality. The examples show a tooltip and an icon, close a window, show a message box and centera window on the desktop.

PyQt5 from riverbank. Contribute to baoboa/pyqt5 development by creating an account on GitHub. How signals and slots are useful, and what they can do when developing in PySide/PyQt. An introduction to creating PySide/PyQt signals and slots, using QObject. How signals and slots are useful, and what they can do when developing in PySide/PyQt. A Simple PySide/PyQt Signal Emitting Example. Let's define a simple PunchingBag class that.

If an event takes place, each PyQt5 widget can emit a signal. A signal does not execute any action, that is done by a slot. Related course: Create GUI Apps with PyQt5; Signals and slot introduction Consider this example. Defining custom slots and signals uses slightly different syntax between the two libraries. PySide2 provides this interface under the names Signal and Slot while PyQt5 provides these as pyqtSignal and pyqtSlot respectively. The behaviour of them both is identical for defining and slots and signals. The following PyQt5 and PySide2 examples are.

Simple example

This is a simple example showing a small window. Yet we can do a lotwith this window. We can resize it, maximise it or minimise it. This requires a lot of coding. Someone already coded this functionality. Because it is repeated in most applications, there is no need to code it over again. PyQt5 is a high level toolkit. If we would code in a lower level toolkit, the following code example could easily have hundreds of lines.

simple.py

The above code example shows a small window on the screen.

Here we provide the necessary imports. The basic widgets are located in PyQt5.QtWidgets module.

Every PyQt5 application must create an application object. The sys.argv parameter is a list of arguments from a command line. Python scripts can be run from the shell. It is a way how we can control the startup of our scripts.

The QWidget widget is the base class of all user interface objects in PyQt5. We provide the default constructor for QWidget. The default constructor has no parent. A widget with no parent is called a window.

The resize() method resizes the widget. It is 250px wide and 150px high.

The move() method moves the widget to a positionon the screen at x=300, y=300 coordinates.

We set the title of the window with setWindowTitle(). The title is shown in the titlebar.

The show() method displays the widget on the screen. A widget is first created in memory and later shown on the screen.

Finally, we enter the mainloop of the application. The event handling starts from this point. The mainloop receives events from the window system and dispatches them to the application widgets.The mainloop ends if we call the exit() method or the main widget is destroyed. The sys.exit() method ensures a clean exit. The environment will be informed how the application ended.

The exec_() method has an underscore. It is because the exec is a Python keyword. And thus, exec_() was used instead.

An application icon

The application icon is a small image which is usually displayedin the top left corner of the titlebar. In the following example we will show how we do it in PyQt5. We will also introduce some new methods.

Some environments do not display icons in the titlebars. We need to enable them.See my answeron Stackoverflow for a solution, if you are seeing no icons.

The previous example was coded in a procedural style. Python programming language supports both procedural and object oriented programming styles. Programming in PyQt5 means programming in OOP.

Three important things in object oriented programming are classes, data, and methods. Here we create a new class called Example. The Example class inherits from the QWidget class. This means that we call two constructors: the first one for the Example class and the second one for the inherited class. The super()method returns the parent object of the Example class and we call its constructor. The __init__() method is a constructor method in Python language.

The creation of the GUI is delegated to the initUI() method.

All three methods have been inherited from the QWidget class. The setGeometry() does two things: it locates the window on the screen and sets it size. The first two parameters are the x and y positions of the window. The third is the width and the fourth is the height of the window. In fact, it combines the resize() and move() methods in one method. The last method sets the application icon. To do this, we have created a QIcon object. The QIcon receives the path to our icon to be displayed.

The application and example objects are created. The main loop is started.

Showing a tooltip

We can provide a balloon help for any of our widgets.

tooltip.py

In this example, we show a tooltip for two PyQt5 widgets.

This static method sets a font used to render tooltips.We use a 10pt SansSerif font.

To create a tooltip, we call the setTooltip() method. We can use rich text formatting.

We create a push button widget and set a tooltip for it.

The button is being resized and moved on the window. The sizeHint()method gives a recommended size for the button.

Signal

Closing a window

The obvious way to close a window is to click on the x mark on the titlebar. In the next example, we show how we can programatically close our window.We will briefly touch signals and slots.

The following is the constructor of a QPushButton widget that we use in our example.

The text parameter is a text that will be displayed on the button. The parent is a widget on which we place our button. In our case it will be a QWidget. Widgets of an application form a hierarchy.In this hierarchy, most widgets have their parents. Widgets without parents are toplevel windows.

In this example, we create a quit button. Upon clicking on the button, the application terminates.

We create a push button. The button is an instance of the QPushButton class. The first parameter of the constructor is the label of the button. The second parameter is the parent widget. The parent widget is the Example widget, which is a QWidget by inheritance.

The event processing system in PyQt5 is built with the signal & slot mechanism. If we click on the button, the signal clicked is emitted. The slot can be a Qt slot or any Python callable.

QCoreApplication, which is retrieved with QApplication.instance(), contains the main event loop—it processes and dispatches all events. The clicked signal is connected to the quit() method which terminates the application. The communication is done between two objects: the sender and the receiver. The sender is the push button, the receiver is the application object.

Message Box

By default, if we click on the x button on the titlebar, the QWidget is closed. Sometimes we want to modify this default behaviour. For example, if we have a file opened in an editorto which we did some changes. We show a message box to confirm the action.

messagebox.py

If we close a QWidget, the QCloseEvent is generated. To modify the widget behaviour we need to reimplement the closeEvent() event handler.

We show a message box with two buttons: Yes and No. The first string appears on the titlebar. The second string is the message text displayed by the dialog. The third argument specifies the combination of buttons appearing in the dialog. The last parameter is the default button. It is the button which has initially the keyboard focus. The return value is stored in the reply variable.

Here we test the return value. If we click the Yes button, we accept the event which leads to the closure of the widget and to the termination of the application. Otherwise we ignore the close event.

Centering window on the screen

The following script shows how we can center a window on the desktop screen.

The QDesktopWidget class provides information about the user's desktop, including the screen size.

The code that will center the window is placed in the custom center() method.

We get a rectangle specifying the geometry of the main window. This includes any window frame.

We figure out the screen resolution of our monitor. And from this resolution, we get the center point.

Our rectangle has already its width and height. Now we set the center of the rectangle to the center of the screen. The rectangle's size is unchanged.

We move the top-left point of the application window to the top-left point of the qr rectangle, thus centering the window on our screen.

In this part of the PyQt5 tutorial, we have created simple code examplesin PyQt5.

If you start building Python application with Qt5 you'll soon discover that there are in fact two packages which you can use to do this — PyQt5 and PySide2.

In this short guide I'll run through why exactly this is, whether you need to care (spoiler: you really don't), what the few differences are and how to work around them. By the end you should be comfortable re-using code examples from both PyQt5 and PySide2 tutorials to build your apps, regardless of which package you're using yourself.

Background

Why are there two packages?

PyQt has been developed by Phil Thompson of Riverbank Computing Ltd. for a very long time — supporting versions of Qt going back to 2.x. Back in 2009 Nokia, who owned the Qt toolkit at the time, wanted to have Python bindings for Qt available under the LGPL license (like Qt itself). Unable to come to agreement with Riverbank (who would lose money from this, so fair enough) they then released their own bindings as PySide (also, fair enough).

Edit: it's called PySide because 'side' is Finnish for 'binder' — thanks to Renato Araujo Oliveira Filho in the comments.

The two interfaces were comparable at first but PySide ultimately development lagged behind PyQt. This was particularly noticeable following the release of Qt 5 — the Qt5 version of PyQt (PyQt5) was available from mid-2016, while the first stable release of PySide2 was 2 years later.

It is this delay which explains why many Qt 5 on Python examples use PyQt5 rather than PySide2 — it's not necessarily better, but it existed. However, the Qt project has recently adopted PySide as the official Qt for Python release which should ensure its viability and increase it's popularity going forward.

PyQt5PySide2
Current stable version (2019-06-23)5.125.12
First stable releaseApr 2016Jul 2018
Developed byRiverbank Computing Ltd.Qt
LicenseGPL or commercialLGPL
PlatformsPython 3Python 3 and Python 2.7 (Linux and MacOS only)

Which should you use? Well, honestly, it doesn't really matter.

Tutorial Pyqt5 Signals And Slots

Both packages are wrapping the same library — Qt5 — and so have 99.9% identical APIs (see below for the few differences). Code that is written for one can often be used as-is with other, simply changing the imports from PyQt5 to PySide2. Anything you learn for one library will be easily applied to a project using the other.

Also, no matter with one you choose to use, it's worth familiarising yourself with the other so you can make the best use of all available online resources — using PyQt5 tutorials to build your PySide2 applications for example, and vice versa.

In this short chapter I'll run through the few notable differences between the two packages and explain how to write code which works seamlessly with both. After reading this you should be able to take any PyQt5 example online and convert it to work with PySide2.

Licensing

The key difference in the two versions — in fact the entire reason PySide2 exists — is licensing. PyQt5 is available under a GPL or commercial license, and PySide2 under a LGPL license.

If you are planning to release your software itself under the GPL, or you are developing software which will not be distributed, the GPL requirement of PyQt5 is unlikely to be an issue. However, if you plan to distribute your software commercially you will either need to purchase a commercial license from Riverbank for PyQt5 or use PySide2.

Qt itself is available under a Qt Commercial License, GPL 2.0, GPL 3.0 and LGPL 3.0 licenses.

Python versions

  • PyQt5 is Python 3 only
  • PySide2 is available for Python3 and Python 2.7, but Python 2.7 builds are only available for 64 bit versions of MacOS and Linux. Windows 32 bit is supported on Python 2 only.

UI files

Both packages use slightly different approaches for loading .ui files exported from Qt Creator/Designer. PyQt5 provides the uic submodule which can be used to load UI files directly, to produce an object. This feels pretty Pythonic (if you ignore the camelCase).

The equivalent with PySide2 is one line longer, since you need to create a QUILoader object first. Unfortunately the api of these two interfaces is different too (.load vs .loadUI) and take different parameters.

To load a UI onto an object in PyQt5, for example in your QMainWindow.__init__, you can call uic.loadUI passing in self (the target widget) as the second parameter.

The PySide2 loader does not support this — the second parameter to .load is the parent widget of the widget you're creating. This prevents you adding custom code to the __init__ block of the widget, but you can work around this with a separate function.

Converting UI files to Python

Both libraries provide identical scripts to generate Python importable modules from Qt Designer .ui files. For PyQt5 the script is named pyuic5

You can then import the UI_MainWindow object, subclass using multiple inheritance from the base class you're using (e.g. QMainWIndow) and then call self.setupUI(self) to set the UI up.

For PySide2 it is named pyside2-uic

The subsequent setup is identical.

Free no deposit bonus codes for cool cat casino. Further down is a ticker that keeps track of the latest winners and the current value of the jackpot games.There’s a generous bonus to welcome new players in addition to a no-deposit bonus. The layout is simple with sliding panels to advertise its enticing welcome bonus and new games to check out.

For more information on using Qt Designer with either PyQt5 or PySide2 see the Qt Creator tutorial.

exec() or exec_()

Pyqt5 Signals And Slots Example 1

The .exec() method is used in Qt to start the event loop of your QApplication or dialog boxes. In Python 2.7 exec was a keyword, meaning it could not be used for variable, function or method names. The solution used in both PyQt4 and PySide was to rename uses of .exec to .exec_() to avoid this conflict.

Python 3 removed the exec keyword, freeing the name up to be used. As PyQt5 targets only Python 3 it could remove the workaround, and .exec() calls are named just as in Qt itself. However, the .exec_() names are maintained for backwards compatibility.

PySide2 is available on both Python 3 and Python 2.7 and so still uses .exec_(). It is however only available for 64bit Linux and Mac.

If you're targeting both PySide2 and PyQt5 use .exec_()

Slots and Signals

Defining custom slots and signals uses slightly different syntax between the two libraries. PySide2 provides this interface under the names Signal and Slot while PyQt5 provides these as pyqtSignal and pyqtSlot respectively. The behaviour of them both is identical for defining and slots and signals.

The following PyQt5 and PySide2 examples are identical —

Or for a slot —

If you want to ensure consistency across PyQt5 and PySide2 you can use the following import pattern for PyQt5 to use the Signal and @Slot style there too.

You could of course do the reverse from PySide2.QtCore import Signal as pyqtSignal, Slot as pyqtSlot although that's a bit confusing.

Pyqt5 Signals And Slots Example Free

You don't need to worry about this if you're writing a standalone app, just use whichever API you prefer.

If you're writing a library, widget or other tool you want to be compatible with both PyQt5 and PySide2 you can do so easily by adding both sets of imports.

This is the approach used in our custom widgets library, where we support for PyQt5 and PySide2 with a single library import. The only caveat is that you must ensure PyQt5 is imported before (as in on the line above or earlier) when importing this library, to ensure it is in sys.modules.

An alternative would be to use an environment variable to switch between them — see QtPy later.

If you're doing this in multiple files it can get a bit cumbersome. A nice solution to this is to move the import logic to its own file, e.g. named qt.py in your project root. This module imports the Qt modules (QtCore, QtGui, QtWidgets, etc.) from one of the two libraries, and then you import into your application from there.

The contents of the qt.py are the same as we used earlier —

You must remember to add any other PyQt5 modules you use (browser, multimedia, etc.) in both branches of the if block. You can then import Qt5 into your own application with —

Pyqt5 Disconnect

…and it will work seamlessly across either library.

Pyqt5 Signals And Slots Example List

QtPy

If you need to target more than just Qt5 support (e.g. including PyQt4 and PySide v1) take a look at QtPy. This provides a standardised PySide2-like API for PyQt4, PySide, PyQt5 and PySide2. Using QtPy you can control which API to load from your application using the QT_API environment variable e.g.

That's really it

There's not much more to say — the two are really very similar. With the above tips you should feel comfortable taking code examples or documentation from PyQt5 and using it to write an app with PySide2. If you do stumble across any PyQt5 or PySide2 examples which you can't easily convert, drop a note in the comments and I'll update this page with advice.

Coments are closed
Scroll to top