PyQt Widgets Tutorial 🎯

beginner
20 min

PyQt Widgets Tutorial 🎯

PyQt is a set of Python bindings for the cross-platform widget toolkit Qt. In this tutorial, we will dive into PyQt widgets, understand their purpose, and learn how to create and customize them.

Understanding PyQt Widgets 📝

Widgets are graphical user interface (GUI) elements that allow users to interact with your applications. PyQt provides various widgets such as buttons, labels, checkboxes, etc., to create rich, interactive applications.

Creating a Simple PyQt Application ✅

Before we dive into widgets, let's create a basic PyQt application.

python
from PyQt5.QtWidgets import QApplication, QWidget import sys class MyApp(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.setWindowTitle('My First PyQt Application') self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = MyApp() sys.exit(app.exec_())

When you run this code, you'll see a simple window titled "My First PyQt Application".

Common PyQt Widgets 📝

Label

A label is a widget that displays text or an icon. Here's an example:

python
from PyQt5.QtWidgets import QApplication, QLabel, QWidget import sys class MyApp(QWidget): def __init__(self): super().__init__() self.initUI() self.label = QLabel('Welcome to PyQt Widgets!', self) self.label.move(50, 50) def initUI(self): self.setWindowTitle('PyQt Widgets') self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = MyApp() sys.exit(app.exec_())

Button

A button is a widget that triggers an action when clicked. Here's an example:

python
from PyQt5.QtWidgets import QApplication, QLabel, QPushButton, QWidget import sys class MyApp(QWidget): def __init__(self): super().__init__() self.initUI() self.label = QLabel('Welcome to PyQt Widgets!', self) self.label.move(50, 50) self.button = QPushButton('Click me!', self) self.button.clicked.connect(self.button_clicked) self.button.move(100, 100) def button_clicked(self): print('Button clicked!') def initUI(self): self.setWindowTitle('PyQt Widgets') self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = MyApp() sys.exit(app.exec_())

In the above example, when you click the button, "Button clicked!" is printed to the console.

Quiz 💡

Quick Quiz
Question 1 of 1

What is the purpose of a PyQt widget?

Conclusion 📝

In this tutorial, we've learned about PyQt widgets, created a simple PyQt application, and explored the label and button widgets. Stay tuned for more advanced PyQt widgets in our upcoming tutorials!