PyQt hello world
Python programming is quite easy, but it could be easier if we had access to a graphical interface for it. By the end of this tutorial, you will have accessed your first Python GUI application, and you’ll have done so in less than one minute.
Step 1: Install Python
Apple Mac OS X
To install the latest version of Python 3 on macOS, do the following:
Download the .dmg file from https://www.python.org/downloads/mac-osx/
Open the .dmg file and run the installer.
To open a terminal window with Python 3 installed, run: python3
Additional instructions can be found at https://docs.python.org/3/using/mac.
If you want to install Python 3 on your Windows machine, there are a few steps you need to take.
Go to the Python website at https://www.python.org/downloads/windows/.
Click on the download link for Windows under the heading “Download the latest Python 3 release.” This will open a new page with a variety of download options.
Choose the one that says “Windows x86-64 executable installer” and wait for it to finish downloading.
Once it’s done, run the installer by double-clicking on it. Follow the prompts and choose all of the default options.
After Python is finished installing, open your Start menu and search for “IDLE (Python 3.7 64-bit)”.
This is a program that comes with Python and allows you to write and execute code in a graphical interface. Double-click on it to launch IDLE; once it’s open, you can start writing code!
Installing Python on Linux is usually pretty straightforward. For most Debian-based distributions, you can just open up a terminal window and type
sudo apt-get install python3
This will install the latest version of Python 3; if you want to install a specific version, you can add its number after “python3,” like this:
sudo apt-get install python3.6
Once the installation is finished, you can launch IDLE by typing “idle3” in the terminal.
To run a script you can type:
Step 2: Install PyQt
python-qt5 is the Python bindings of Qt5, the cross-platform application and user interface development toolkit. This module provides Python language bindings for Qt5. Python-Qt5 gives Python bindings for Qt5.
Setting up this module is relatively simple and can be done through a few different methods. The most common way to install Python-Qt5 is by using a package manager such as pip.
Regardless of which method you choose, once everything is set up, you will be able to start writing code that utilizes the full power of Qt5!
pip install pyqt5 pyqt5-tools
On Debian/Ubuntu you can also use:
sudo apt install python3-pyqt5
Step 3: Write the code
The program below needs to be saved with the .py extension. The second line loads the PyQt5 module.
import sys from PyQt5.QtWidgets import QApplication, QWidget if __name__ == '__main__': # create PyQt app app = QApplication(sys.argv) # Create widget to draw in w = QWidget() # Set window size w.resize(250, 150) # Move window w.move(300, 300) # Set window title w.setWindowTitle('Hello World') # Show window w.show() # Run application sys.exit(app.exec_())
Run the program with Python. The last line starts the app. As a desktop app, PyQt waits for events and keeps running until the program is closed.
Instead of QWidget, the class QMainWindow is often used. The window can contain many different widgets like labels, buttons, images and more.
You can add a label in the window, which shows the text. To show text, use QLabel which is part of QtWidgets.
# importing the required libraries from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the window title self.setWindowTitle("hello!") # set the window width and height self.setGeometry(0, 0, 320, 200) # create label to display text self.label = QLabel("Hello World", self) # show all the widgets self.show() # create pyqt5 app App = QApplication(sys.argv) # create our Window window = Window() # start app sys.exit(App.exec())
This creates a window with the title and the label.
QLabel is a widget that displays text or an image. In Qt5, it can also display rich text, that is, HTML content.
A QLabel can contain any of the HTML tags supported by QtWebKit, including images and links. For example:
label = QLabel() label.setText("<a href=\"http://www.google.com\">Google")
You can also set the QLabel to display an animated image by calling the setMovie() function with a QMovie object as argument. For example:
movie = QMovie("animated.gif") label = QLabel() label.setMovie(movie)
The program below displays an animated gif inside a QLabel.
import sys from PyQt5.QtCore import Qt, QByteArray, QSettings, QTimer, pyqtSlot from PyQt5.QtWidgets import QWidget, QApplication, QLabel, QSizePolicy, QVBoxLayout, QAction, QPushButton from PyQt5.QtGui import QMovie gifFile = "world.gif" class GifPlayer(QWidget): def __init__(self, title, gifFile, parent=None): QWidget.__init__(self, parent) self.movie = QMovie(gifFile, QByteArray(), self) size = self.movie.scaledSize() self.setGeometry(200, 200, size.width(), size.height()) self.setWindowTitle(title) self.movie_screen = QLabel() self.movie_screen.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.movie_screen.setAlignment(Qt.AlignCenter) main_layout = QVBoxLayout() main_layout.addWidget(self.movie_screen) self.setLayout(main_layout) self.movie.setCacheMode(QMovie.CacheAll) self.movie_screen.setMovie(self.movie) self.movie.start() self.movie.loopCount() if __name__ == "__main__": app = QApplication(sys.argv) player = GifPlayer("update this gif", "world.gif") player.show() sys.exit(app.exec_())
This displays an animated gif in your window. Could be a spinning earth gif or anything else.
That’s all there is to hello world. However, there is a lot more to GUI programming and PyQt.