Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python PyQt

Python PyQt

PyQt is a powerful Python library for creating graphical user interfaces (GUIs) and can be used in place of Python's built-in Tkinter.

PyQt is the Python binding for the Qt framework and is widely used in desktop application development.

Qt is a cross-platform C++ application development framework.

PyQt lets Python developers use the Qt library to build powerful GUI applications.

PyQt has the following major versions:

Installing PyQt

Install PyQt5 with pip:


# 安装PyQt5
pip install PyQt5

# Install Qt Designer and other tools (optional)
pip install PyQt5-tools

The first PyQt program

Create a simple window

The following is the most basic PyQt program, which creates an empty window:

Example

from

PyQt5.

QtCore

import

Qt

from

PyQt5.

QtWidgets

import

QApplication

,

QWidget

Create application instance

app

=

QApplication

(

[

]

)

Create the main window

window

=

QWidget

(

)

window.

setWindowTitle

(

"My First PyQt Program"

)

window.

setGeometry

(

100

,

100

,

400

,

300

)

 

(x, y, width, height)

window.

setAttribute

(

Qt.

WA_DeleteOnClose

,

True

)

Destroy

Show the window

window.

show

(

)

Run the application

app.

exec_

(

)

Code Analysis

  1. QApplication: Manages the control flow and main settings of a GUI application.
  2. QWidget: The most basic window class; all UI widgets inherit from it.
  3. setWindowTitle(): Sets the window title.
  4. setGeometry(): Sets the window position and size.
  5. show(): Shows the window.
  6. app.exec_(): Starts the event loop and waits for user interaction.

A typical PyQt application consists of the following parts:

  1. QApplication object: Every PyQt application needs a QApplication instance
  2. Windows and widgets: User interface components
  3. Event loop: The loop that handles user input and system events
  4. Event handlers: Functions or methods that respond to events

Example

import

sys

from

PyQt5.

QtWidgets

import

QApplication

,

QMainWindow

,

QPushButton

class

MainWindow

(

QMainWindow

)

:

   

def

init

(

self

)

:

       

super

(

)

.

init

(

)

       

       

Set the window title and size

       

self

.

setWindowTitle

(

"My First PyQt App"

)

       

self

.

setGeometry

(

100

,

100

,

400

,

300

)

 

x, y, width, height

       

       

Create a button

       

self

.

button

=

QPushButton

(

"Click me"

,

self

)

       

self

.

button

.

setGeometry

(

150

,

150

,

100

,

30

)

       

self

.

button

.

clicked

.

connect

(

self

.

button_clicked

)

       

   

def

button_clicked

(

self

)

:

       

print

(

"Button clicked!"

)

if

name

==

"main"

:

    app

=

QApplication

(

sys

.

argv

)

    window

=

MainWindow

(

)

    window.

show

(

)

   

sys

.

exit

(

app.

exec_

(

)

)


Common PyQt widgets

Button (QPushButton)

Example

from

PyQt5.

QtWidgets

import

QPushButton

button

=

QPushButton

(

"Click me"

,

window

)

button.

move

(

150

,

150

)

 

Set the button position

Label (QLabel)

Example

from

PyQt5.

QtWidgets

import

QLabel

label

=

QLabel

(

"Hello PyQt!"

,

window

)

label.

move

(

100

,

100

)

Text box (QLineEdit)

Example

from

PyQt5.

QtWidgets

import

QLineEdit

textbox

=

QLineEdit

(

window

)

textbox.

move

(

100

,

50

)

For more on common widgets, see:https://www.runoob.com/python3/python-pyqt-widgets.html


Layout management (QVBoxLayout)

A layout manager can adjust widget positions automatically:

Example

from

PyQt5.

QtWidgets

import

QVBoxLayout

,

QLabel

,

QPushButton

layout

=

QVBoxLayout

(

)

layout.

addWidget

(

QLabel

(

"Username"

)

)

layout.

addWidget

(

QLineEdit

(

)

)

layout.

addWidget

(

QPushButton

(

"Login"

)

)

window.

setLayout

(

layout

)

For more on layout management, see:https://www.runoob.com/python3/python-pyqt-layout.html


Signals and slots

PyQt uses the **SignalandSlot** mechanism to handle events.

PyQt's signals and slots mechanism is the core mechanism for communication between objects.

Example

from

PyQt5.

QtWidgets

import

QPushButton

def

on_button_click

(

)

:

   

print

(

"Button clicked!"

)

button

=

QPushButton

(

"Click me"

,

window

)

button.

clicked

.

connect

(

on_button_click

)

 

Connect a signal and a slot

Custom signals

Example

from

PyQt5.

QtCore

import

pyqtSignal

,

QObject

class

MyEmitter

(

QObject

)

:

    my_signal

=

pyqtSignal

(

str

)

 

Define a signal

emitter

=

MyEmitter

(

)

emitter.

my_signal

.

connect

(

lambda

x:

print

(

f

"Signal received: {x}"

)

)

emitter.

my_signal

.

emit

(

"Hello"

)

 

Trigger the signal

For more on layout management, see:https://www.runoob.com/python3/python-pyqt-signals-and-slots.html


Using Qt Designer

Qt Designer is a visual design tool that lets you drag and drop widgets to design an interface:

Use the generated interface in code:

Example

from

PyQt5

import

uic

Load the UI file

Form

,

Window

=

uic.

loadUiType

(

"output.ui"

)

Use the UI

app

=

QApplication

(

sys

.

argv

)

window

=

Window

(

)

form

=

Form

(

)

form.

setupUi

(

window

)

window.

show

(

)

sys

.

exit

(

app.

exec_

(

)

)


Hands-on: a simple notepad application

Interface design

Example

import

sys

from

PyQt5.

QtWidgets

import

(

QApplication

,

QMainWindow

,

QTextEdit

,

                            QAction

,

QFileDialog

,

QMessageBox

)

class

Notepad

(

QMainWindow

)

:

   

def

init

(

self

)

:

       

super

(

)

.

init

(

)

       

self

.

initUI

(

)

       

   

def

initUI

(

self

)

:

       

self

.

text_edit

=

QTextEdit

(

self

)

       

self

.

setCentralWidget

(

self

.

text_edit

)

       

       

self

.

create_actions

(

)

       

self

.

create_menus

(

)

       

       

self

.

setWindowTitle

(

'Simple Notepad'

)

       

self

.

setGeometry

(

100

,

100

,

800

,

600

)

       

   

def

create_actions

(

self

)

:

       

File menu actions

       

self

.

new_action

=

QAction

(

'New'

,

self

)

       

self

.

new_action

.

setShortcut

(

'Ctrl+N'

)

       

self

.

new_action

.

triggered

.

connect

(

self

.

new_file

)

       

       

self

.

open_action

=

QAction

(

'Open'

,

self

)

       

self

.

open_action

.

setShortcut

(

'Ctrl+O'

)

       

self

.

open_action

.

triggered

.

connect

(

self

.

open_file

)

       

       

self

.

save_action

=

QAction

(

'Save'

,

self

)

       

self

.

save_action

.

setShortcut

(

'Ctrl+S'

)

       

self

.

save_action

.

triggered

.

connect

(

self

.

save_file

)

       

       

self

.

exit_action

=

QAction

(

'Exit'

,

self

)

       

self

.

exit_action

.

setShortcut

(

'Ctrl+Q'

)

       

self

.

exit_action

.

triggered

.

connect

(

self

.

close

)

       

       

Edit menu actions

       

self

.

copy_action

=

QAction

(

'Copy'

,

self

)

       

self

.

copy_action

.

setShortcut

(

'Ctrl+C'

)

       

self

.

copy_action

.

triggered

.

connect

(

self

.

text_edit

.

copy

)

       

       

self

.

paste_action

=

QAction

(

'Paste'

,

self

)

       

self

.

paste_action

.

setShortcut

(

'Ctrl+V'

)

       

self

.

paste_action

.

triggered

.

connect

(

self

.

text_edit

.

paste

)

       

       

self

.

cut_action

=

QAction

(

'Cut'

,

self

)

       

self

.

cut_action

.

setShortcut

(

'Ctrl+X'

)

       

self

.

cut_action

.

triggered

.

connect

(

self

.

text_edit

.

cut

)

       

   

def

create_menus

(

self

)

:

        menubar

=

self

.

menuBar

(

)

       

       

File menu

        file_menu

=

menubar.

addMenu

(

'File'

)

        file_menu.

addAction

(

self

.

new_action

)

        file_menu.

addAction

(

self

.

open_action

)

        file_menu.

addAction

(

self

.

save_action

)

        file_menu.

addSeparator

(

)

        file_menu.

addAction

(

self

.

exit_action

)

       

       

Edit menu

        edit_menu

=

menubar.

addMenu

(

'Edit'

)

        edit_menu.

addAction

(

self

.

copy_action

)

        edit_menu.

addAction

(

self

.

paste_action

)

        edit_menu.

addAction

(

self

.

cut_action

)

       

   

def

new_file

(

self

)

:

       

self

.

text_edit

.

clear

(

)

       

   

def

open_file

(

self

)

:

        filename

,

_

=

QFileDialog.

getOpenFileName

(

self

,

'Open file'

)

       

if

filename:

           

try

:

               

with

open

(

filename

,

'r'

)

as

f:

                   

self

.

text_edit

.

setText

(

f.

read

(

)

)

           

except

Exception

as

e:

                QMessageBox.

warning

(

self

,

'Error'

,

f

'Cannot open file: {e}'

)

               

   

def

save_file

(

self

)

:

        filename

,

_

=

QFileDialog.

getSaveFileName

(

self

,

'Save file'

)

       

if

filename:

           

try

:

               

with

open

(

filename

,

'w'

)

as

f:

                    f.

write

(

self

.

text_edit

.

toPlainText

(

)

)

           

except

Exception

as

e:

                QMessageBox.

warning

(

self

,

'Error'

,

f

'Cannot save file: {e}'

)

if

name

==

'main'

:

    app

=

QApplication

(

sys

.

argv

)

    notepad

=

Notepad

(

)

    notepad.

show

(

)

   

sys

.

exit

(

app.

exec_

(

)

)


Core PyQt5 widgets

Most widgets live in PyQt5.QtWidgets.

Advanced features (such as multimedia and networking) may require other modules (such as QtCore, QtGui, QtNetwork, etc.).

QListView/QTableView/QTreeView need to be used with a data model (such as QStandardItemModel), which offers greater flexibility.

Other installation extensions:


pip install PyQtWebEngine  # 网页支持
pip install PyQtChart      # 图表支持
Widget category Component name Module Description
Basic window widgets QWidget QtWidgets Base class of all user interface objects; can be used as a blank window or container
QMainWindow QtWidgets Main window framework, including a menu bar, toolbars, status bar, etc.
QDialog QtWidgets Base class for dialogs, used for pop-up windows
layout management QVBoxLayout QtWidgets Vertical layout manager
QHBoxLayout QtWidgets Horizontal layout manager
QGridLayout QtWidgets Grid layout manager
QFormLayout QtWidgets Form layout manager (label + input field pairs)
Buttons QPushButton QtWidgets Normal button
QRadioButton QtWidgets Radio Button
QCheckBox QtWidgets Checkbox
QToolButton QtWidgets Toolbar button (can carry an icon)
Input controls QLineEdit QtWidgets Single-line text input
QTextEdit QtWidgets Multi-line rich text editor (supports HTML)
QPlainTextEdit QtWidgets Multi-line plain text editor
QSpinBox QtWidgets Spin box (integers)
QDoubleSpinBox QtWidgets Spin box (floating-point numbers)
QComboBox QtWidgets Drop-down selection box
QDateEdit QtWidgets Date picker
QTimeEdit QtWidgets Time picker
QDateTimeEdit QtWidgets Date-time picker
QSlider QtWidgets Slider (horizontal / vertical)
QDial QtWidgets Circular dial control
Display controls QLabel QtWidgets Text / image label
QLCDNumber QtWidgets LCD numeric display
QProgressBar QtWidgets Progress bar
QStatusBar QtWidgets Status bar (usually used inQMainWindow)
Containers QGroupBox QtWidgets Group box (a container with a title)
QTabWidget QtWidgets Tab container
QStackedWidget QtWidgets Stacked container (shows one child widget at a time)
QScrollArea QtWidgets Scroll area container
QMdiArea QtWidgets MDI (multiple document interface) area
List / table / tree QListWidget QtWidgets List widget (with item management)
QTreeWidget QtWidgets Tree widget
QTableWidget QtWidgets Table widget
QListView QtWidgets List view (requires a data model)
QTableView QtWidgets Table view (requires a data model)
QTreeView QtWidgets Tree view (requires a data model)
Menus / toolbars QMenuBar QtWidgets Menu bar
QMenu QtWidgets Menu (can contain submenus and actions)
QToolBar QtWidgets Toolbar
QAction QtWidgets Action (used for menu items, toolbar buttons, etc.)
Dialogs QFileDialog QtWidgets File selection dialog
QColorDialog QtWidgets Color selection dialog
QFontDialog QtWidgets Font selection dialog
QInputDialog QtWidgets Input dialog (text, numbers, etc.)
QMessageBox QtWidgets Message box (warning, error, question, etc.)
Graphics view QGraphicsView QtWidgets Graphics view framework (for 2D graphics)
QGraphicsScene QtWidgets Graphics scene (used together withQGraphicsView)
Other functional widgets QCalendarWidget QtWidgets Calendar widget
QSplashScreen QtWidgets Splash screen
QSystemTrayIcon QtWidgets System tray icon
QWebEngineView QtWebEngineWidgets Web browser widget (requires a separate installation ofPyQtWebEngine)

Learning resources