Frontend Development 8 min read

Ten PyQt5 GUI Widget Examples for Desktop Applications

This article provides ten self‑contained PyQt5 examples—including a simple window, button counter, text input, checkbox, combo box, file dialog, progress bar, label, table view, and calendar widget—each with full Python code and brief explanations for building desktop GUI components.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Ten PyQt5 GUI Widget Examples for Desktop Applications

1. Simple Window

A minimal PyQt5 window that sets a title and displays the widget.

from PyQt5.QtWidgets import QApplication, QWidget
if __name__ == '__main__':
    app = QApplication([])  # 创建应用程序对象
    window = QWidget()      # 创建一个窗口部件
    window.setWindowTitle('我的第一个PyQt窗口')  # 设置窗口标题
    window.show()           # 显示窗口
    print("窗口已显示")
    app.exec_()             # 进入主事件循环

2. Button Click Counter

A widget with a button that increments a counter each time it is clicked.

from PyQt5.QtWidgets import QApplication, QPushButton, QVBoxLayout, QWidget
class CounterWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.count = 0
        layout = QVBoxLayout()
        self.button = QPushButton('点击我')
        self.button.clicked.connect(self.increment)
        layout.addWidget(self.button)
        self.setLayout(layout)
    def increment(self):
        self.count += 1
        print(f"按钮被点击了 {self.count} 次")
if __name__ == '__main__':
    app = QApplication([])
    widget = CounterWidget()
    widget.setWindowTitle('按钮点击计数器')
    widget.show()
    app.exec_()

3. Text Input

A widget that shows a QLineEdit with placeholder text.

from PyQt5.QtWidgets import QApplication, QLineEdit, QVBoxLayout, QWidget
class TextInputWidget(QWidget):
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()
        self.text_input = QLineEdit(self)
        self.text_input.setPlaceholderText("请输入一些文字...")
        layout.addWidget(self.text_input)
        self.setLayout(layout)
if __name__ == '__main__':
    app = QApplication([])
    widget = TextInputWidget()
    widget.setWindowTitle('文本输入框')
    widget.show()
    app.exec_()

4. Checkbox

A simple checkbox that prints a message when its state changes.

from PyQt5.QtWidgets import QApplication, QCheckBox, QVBoxLayout, QWidget
class CheckBoxWidget(QWidget):
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()
        self.check_box = QCheckBox('勾选我')
        self.check_box.stateChanged.connect(lambda: print("复选框状态改变"))
        layout.addWidget(self.check_box)
        self.setLayout(layout)
if __name__ == '__main__':
    app = QApplication([])
    widget = CheckBoxWidget()
    widget.setWindowTitle('复选框示例')
    widget.show()
    app.exec_()

5. Combo Box

A drop‑down menu with three items that reports the selected item.

from PyQt5.QtWidgets import QApplication, QComboBox, QVBoxLayout, QWidget
class ComboBoxWidget(QWidget):
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()
        self.combo_box = QComboBox()
        self.combo_box.addItems(['选项一', '选项二', '选项三'])
        self.combo_box.currentIndexChanged.connect(lambda: print(f"选择了 {self.combo_box.currentText()}"))
        layout.addWidget(self.combo_box)
        self.setLayout(layout)
if __name__ == '__main__':
    app = QApplication([])
    widget = ComboBoxWidget()
    widget.setWindowTitle('下拉菜单')
    widget.show()
    app.exec_()

6. File Dialog

A button that opens a file‑selection dialog and prints the chosen file path.

from PyQt5.QtWidgets import QApplication, QPushButton, QVBoxLayout, QWidget, QFileDialog
class FileDialogWidget(QWidget):
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()
        button = QPushButton('打开文件')
        button.clicked.connect(self.open_file_dialog)
        layout.addWidget(button)
        self.setLayout(layout)
    def open_file_dialog(self):
        file_name, _ = QFileDialog.getOpenFileName(self, "选择文件", "", "所有文件 (*)")
        if file_name:
            print(f"选择了文件: {file_name}")
if __name__ == '__main__':
    app = QApplication([])
    widget = FileDialogWidget()
    widget.setWindowTitle('文件对话框')
    widget.show()
    app.exec_()

7. Progress Bar

A progress bar that updates from 0 to 100 when a button is pressed.

from PyQt5.QtWidgets import QApplication, QProgressBar, QPushButton, QVBoxLayout, QWidget
class ProgressBarWidget(QWidget):
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()
        self.progress_bar = QProgressBar()
        self.progress_bar.setValue(0)
        button = QPushButton('开始')
        button.clicked.connect(self.start_progress)
        layout.addWidget(self.progress_bar)
        layout.addWidget(button)
        self.setLayout(layout)
    def start_progress(self):
        for i in range(101):
            self.progress_bar.setValue(i)
            print(f"进度: {i}%")
            QApplication.processEvents()
if __name__ == '__main__':
    app = QApplication([])
    widget = ProgressBarWidget()
    widget.setWindowTitle('进度条')
    widget.show()
    app.exec_()

8. Label

A widget that displays a static text label.

from PyQt5.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
class LabelWidget(QWidget):
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()
        label = QLabel('这是一个标签')
        layout.addWidget(label)
        self.setLayout(layout)
if __name__ == '__main__':
    app = QApplication([])
    widget = LabelWidget()
    widget.setWindowTitle('标签显示')
    widget.show()
    app.exec_()

9. Table View

A QTableView populated with a 4×2 model showing sample rows and columns.

from PyQt5.QtWidgets import QApplication, QTableView, QWidget, QVBoxLayout
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QStandardItemModel, QStandardItem

class TableViewWidget(QWidget):
    def __init__(self):
        super().__init__()
        model = QStandardItemModel(4, 2)
        model.setHorizontalHeaderLabels(['列1', '列2'])
        for row in range(4):
            for column in range(2):
                item = QStandardItem(f'Row {row+1}, Column {column+1}')
                model.setItem(row, column, item)
        table_view = QTableView()
        table_view.setModel(model)
        layout = QVBoxLayout()
        layout.addWidget(table_view)
        self.setLayout(layout)

if __name__ == '__main__':
    app = QApplication([])
    widget = TableViewWidget()
    widget.setWindowTitle('表格视图')
    widget.show()
    app.exec_()

10. Calendar Widget

A calendar that prints the selected date whenever the user changes it.

from PyQt5.QtWidgets import QApplication, QCalendarWidget, QVBoxLayout, QWidget
class CalendarWidget(QWidget):
    def __init__(self):
        super().__init__()
        calendar = QCalendarWidget()
        calendar.selectionChanged.connect(self.print_selected_date)
        layout = QVBoxLayout()
        layout.addWidget(calendar)
        self.setLayout(layout)
    def print_selected_date(self):
        selected_date = self.sender().selectedDate().toString(Qt.ISODate)
        print(f"选择了日期: {selected_date}")
if __name__ == '__main__':
    app = QApplication([])
    widget = CalendarWidget()
    widget.setWindowTitle('日历选择器')
    widget.show()
    app.exec_()

Each snippet can be run independently after installing PyQt5 (or PySide2 ) in a Python environment. Adjust titles, layouts, or widget properties as needed for your own projects.

GUIPythonTutorialDesktopwidgetsPyQt5
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.