Pyqt5, Pyq1 Tutorial – Complete Guide

If you are passionate about programming, game development, or simply building interactive technology solutions, there is a high chance you’ve crossed paths with Python and its versatile libraries. One such powerful library is PyQt5, an essential toolkit for creating sophisticated graphical user interfaces. In this tutorial, we’ll dive into the what, why, and how of PyQt5, alongside engaging examples and analogies.

What is PyQt5?

PyQt5 is a set of Python bindings for Qt libraries which can be used to create cross-platform applications. It combines the best of Python and Qt and presents developers with a framework to build GUI applications in an efficient and modular way.

PyQt5 is primarily used for developing graphical user interfaces for Python applications. However, although it is often associated with GUI development, it’s capabilities exceed that parameter. With its cross-platform availability, it’s a favoured choice for many developers to create applications that run without modifications on various operating systems.

Why Should I Learn PyQt5?

Learning PyQt5 opens doors to diverse opportunities. A few reasons to learn PyQt5 include:

  • Increasing demand for GUI solutions in the modern tech industry makes this a valuable skill.
  • Multi-platform compatibility simplifies the development process saving time and effort.
  • Its powerful, all-inclusive toolset reduces the need for external dependencies.
  • Encourages creativity by enabling developers to create interfaces with a wide range of interactive elements.

By the end of this tutorial, you’ll be equipped with the basics of PyQt5 to kick-start your journey in the world of interactive application development.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Getting Started with PyQt5

Before we dive into coding, ensure that PyQt5 is properly installed on your system. You can install it using pip:

pip install PyQt5

A Basic PyQt5 Example

Let’s start with a simple “Hello, World!” using PyQt5. We’ll create a basic window to demonstrate this.

import sys
from PyQt5.QtWidgets import QApplication, QLabel, QWidget

def window():
   app = QApplication(sys.argv)
   widget = QWidget()

   textLabel = QLabel(widget)
   textLabel.setText("Hello, World!")
   textLabel.move(110,85)

   widget.setWindowTitle("PyQt5 App")
   widget.show()

   sys.exit(app.exec_())

if __name__ == '__main__':
   window()

In this snippet, we first import necessary PyQt5 components. We create a QWidget which will be our main window, and set a QLabel saying “Hello, World!”.

Adding Widgets in PyQt5

Widgets are the building blocks of a PyQt5 GUI application. Let’s add a QPushButton (a clickable button) to our window.

import sys
from PyQt5.QtWidgets import QApplication, QPushButton, QWidget

def window():
   app = QApplication(sys.argv)
   widget = QWidget()

   button = QPushButton(widget)
   button.setText("Click me")
   button.move(110,85)

   widget.setWindowTitle("PyQt5 App")
   widget.show()

   sys.exit(app.exec_())

if __name__ == '__main__':
   window()

In this code snippet, we replace our label with a button which says “Click me”.

Connecting Signals and Slots in PyQt5

Signals and slots are used for communication between objects in PyQt5. Let’s create an application which closes the window if the button is clicked.

import sys
from PyQt5.QtWidgets import QApplication, QPushButton, QWidget

def window():
   app = QApplication(sys.argv)
   widget = QWidget()

   button = QPushButton(widget)
   button.setText("Close App")
   button.clicked.connect(app.exit)
   button.move(110,85)

   widget.setWindowTitle("PyQt5 App")
   widget.show()

   sys.exit(app.exec_())

if __name__ == '__main__':
   window()

Once the user clicks the ‘Close App’ button, the application will close.

Processing User Input with PyQt5

Next, let’s step-up our GUI game with an example of processing user input using QTextEdit field.

import sys
from PyQt5.QtWidgets import QApplication, QPushButton, QTextEdit, QVBoxLayout, QWidget

def window():
   app = QApplication(sys.argv)
   widget = QWidget()

   layout = QVBoxLayout()
   textedit = QTextEdit()
   button = QPushButton("Print Input")

   button.clicked.connect(lambda: print(textedit.toPlainText()))
   layout.addWidget(textedit)
   layout.addWidget(button)

   widget.setLayout(layout)
   widget.setWindowTitle("PyQt5 App")
   widget.show()

   sys.exit(app.exec_())

if __name__ == '__main__':
   window()

In this example, we added a QTextEdit widget, which is a multi-line text input field. The clicked signal of the button is connected to a lambda function that prints the contents of the QTextEdit field.

Adding Logic to Your PyQt5 Application

Let’s create a simple calculator that performs addition on user input.

import sys
from PyQt5.QtWidgets import QApplication, QPushButton, QLineEdit, QVBoxLayout, QWidget

def window():
   app = QApplication(sys.argv)
   widget = QWidget()

   layout = QVBoxLayout()
   input1 = QLineEdit()
   input2 = QLineEdit()
   button = QPushButton("Add")
   result = QLineEdit()

   def adder():
       res = float(input1.text()) + float(input2.text())
       result.setText(str(res))

   button.clicked.connect(adder)
   layout.addWidget(input1)
   layout.addWidget(input2)
   layout.addWidget(button)
   layout.addWidget(result)

   widget.setLayout(layout)
   widget.setWindowTitle("PyQt5 App")
   widget.show()

   sys.exit(app.exec_())

if __name__ == '__main__':
   window()

Here, we used two QLineEdit widgets for inputs and one for the result. If you click the “Add” button, the adder function adds the values in the input fields and displays the result.

Creating Multiple Windows in PyQt5

Often, GUI applications are not limited to a single window. Let’s create an application that opens a new window upon a button click.

import sys
from PyQt5.QtWidgets import QApplication, QPushButton, QVBoxLayout, QWidget

class MainWindow(QWidget):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        
        layout = QVBoxLayout()
        button = QPushButton("Open Second Window")
        button.clicked.connect(self.open_second_window)

        layout.addWidget(button)
        self.setLayout(layout)
        self.setWindowTitle("First Window")

    def open_second_window(self):
        self.second_window = SecondWindow(self)
        self.second_window.show()


class SecondWindow(QWidget):
    def __init__(self, parent=None):
        super(SecondWindow, self).__init__(parent)
        
        self.setWindowTitle("Second Window")


def main():
    app = QApplication(sys.argv)
    main_win = MainWindow()
    main_win.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

This example has two classes for separate windows. The button in MainWindow opens a SecondWindow.

Loading UI Files in PyQt5

In PyQt5, you can also load layout files created using Qt Designer. Here’s an example of how to load a .ui file:

import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.uic import loadUi

class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()
        loadUi('my_layout.ui', self)

def main():
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

In this example, ‘my_layout.ui’ is your .ui filename you have created with Qt Designer. After loading the .ui file, all the widgets defined in the file are available as attributes in the Window instance.

Where to go next?

Now that we’ve scratched the surface of what PyQt5 is capable of, you might be wondering what’s next in your exploration of Python and GUI development. The truth is, the possibilities are endless. Python is a powerful and influential language in today’s tech field and PyQt5, with its interactive capabilities and simplicity in use, is an incredible tool for real-world application development.

So, where do you start? Let us help you continue your journey with our comprehensive Python Mini-Degree. The Python Mini-Degree we offer at Zenva Academy is an extensive suite of courses designed to equip you with Python programming knowledge. This Mini-Degree isn’t limited to just basic coding, it takes you further into the realms of algorithms, object-oriented programming, game development, and sophisticated app creation.

The beauty of our approach is the hands-on methodology. Throughout the courses, you’ll develop your own games, algorithms, and real-world apps, thus solidifying your understanding, improving your coding habits and ending up with a portfolio that stands tall in the job market. There is content available to cater to everyone’s pace, be it a beginner or an experienced developer.

In addition to the Mini-Degree, you have the option to delve into our broader collection of Python courses. From creating interactive stories and games, to data manipulation using Pandas, we cover it all.

Conclusion

Learning PyQt5 navigation and handling can be a game-changer in your Python-based application development journey. Its cross-platform nature and extensive capabilities make it a tool worth mastering, irrespective of your career stage. Remember, every expert was once a beginner who chose not to give up.

Keep nurturing that curiosity and further enhance your Python skill set with Zenva’s extensive and tailored Python Mini-Degree, where our objective is not just to teach, but to facilitate meaningful and knowledge-retaining experiences. Happy coding!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.