Introduction to PyQt/PySide

Introduction to PyQt/PySide in Python: While Tkinter is great for quick tools, most professional Python software (including software used by companies like…

Concept Explanation

While Tkinter is great for quick tools, most professional Python software (including software used by companies like Adobe and Disney) uses PyQt or PySide.

PyQt is based on the industry-standard "Qt" framework. It is much more powerful than Tkinter, offering:

  • Modern Look: Apps look like native Windows 11 or macOS apps.
  • CSS Styling: You can design your app using code that looks exactly like CSS (Web styles).
  • Designer Tool: A "Drag and Drop" visual builder (Qt Designer) so you don't have to code layouts manually.

Syntax or Core Structure

The Application Object

PyQt requires a QApplication to handle system settings and an event loop.

from PyQt6.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout
import sys

# 1. Start the System
app = QApplication(sys.argv)

# 2. Create the Window
window = QWidget()
window.setWindowTitle("PyQt App")

# 3. Create a Layout
layout = QVBoxLayout()
layout.addWidget(QLabel("Hello from PyQt!"))
window.setLayout(layout)

# 4. Show and Run
window.show()
sys.exit(app.exec())

Code Example #1 (Basic)

Adding a Styled Button with Signals and Slots.

from PyQt6.QtWidgets import QPushButton

btn = QPushButton("Click Me")

# PyQt uses "Signals" (.clicked) and "Slots" (the function)
btn.clicked.connect(lambda: print("Clicked!"))

# Adding Styles (CSS format)
btn.setStyleSheet("background-color: #2ecc71; color: white; border-radius: 5px;")

Real World Example

A Modern Dark-Mode Dashboard: Using a layout manager to create a sleek side-bar and main view.

# 🏢 Logic Summary
# 1. Use QMainWindow for the primary structure.
# 2. Add a QListWidget on the left for navigation.
# 3. Use QStackedWidget on the right to switch between different "pages."
# 4. Apply a "Dark Theme" stylesheet to the entire app.

Common Mistakes

  1. Multiple QApplications: You can only have one QApplication instance at a time.
  2. Not using sys.exit(): If you don't use sys.exit(app.exec()), your Python script might finish while the window is still open, causing a crash.
  3. Complex Logic in UI Thread: Like Tkinter, blocking the main thread will freeze your beautiful PyQt window.

Practice Exercises

  1. The Style Master: Create a PyQt window with one Button. Give it a hover effect using CSS (e.g., QPushButton:hover { background-color: blue; }).
  2. The Welcome App: Create a PyQt form that asks for a Name and Age, then prints "Welcome [Name], you are [Age] years old!" in the terminal.
  3. The Image Viewer: Research the QLabel.setPixmap() method and write a script that displays an image file on your computer.