Contents Menu Expand Light mode Dark mode Auto light/dark, in light mode Auto light/dark, in dark mode Skip to content
Qt for Python
Logo
Qt for Python
  • 入门指南
  • 商业用途
  • 从源代码构建
  • 包详情
  • 模块 API
  • 工具
  • Tutorials
  • 示例
    • 扩展QML - 添加类型示例
    • 扩展QML(高级)- 生日派对基础项目
    • 扩展QML(高级)- 继承与强制转换
    • 扩展QML(高级)- 默认属性
    • 扩展QML(高级)- 分组属性
    • 扩展QML(高级)- 附加属性
    • 扩展QML(高级)- 属性值源
    • 扩展QML - 绑定示例
    • 扩展QML - 创建新类型
    • 扩展QML - 连接到C++方法和信号
    • 扩展QML - 添加属性绑定
    • 扩展QML - 使用自定义属性类型
    • 扩展QML - 使用列表属性类型
    • 扩展QML - 插件示例
    • QML中的QAbstractListModel
    • 扩展QML - 扩展对象示例
    • 扩展QML - 方法示例
    • 扩展QML - 对象和列表属性类型示例
    • examples/qml/signals/pytoqml1
    • examples/qml/signals/pytoqml2
    • examples/qml/signals/qmltopy1
    • examples/qml/signals/qmltopy2
    • examples/qml/signals/qmltopy3
    • examples/qml/signals/qmltopy4
    • 文本属性示例
    • 使用模型示例
    • 对象列表模型示例
    • OpenGL under QML Squircle
    • 场景图绘制项示例
    • QQuickRenderControl OpenGL 示例
    • 场景图 - 自定义几何
    • 字符串列表模型示例
    • Qt Quick 示例 - 窗口和屏幕
    • Qt Quick Controls 2 - 画廊
    • Qt Quick Controls - 联系人列表
    • Qt Quick Controls - 文件系统浏览器
    • Widgets Gallery Example
    • 通讯录示例
    • 通讯录示例
    • examples/widgets/graphicsview/anchorlayout
    • 动画瓷砖示例
    • 应用程序选择器示例
    • examples/widgets/mainwindows/application
    • 基本绘图示例
    • examples/widgets/itemviews/basicfiltermodel
    • 基本布局示例
    • 模糊选择器效果示例
    • 边框布局示例
    • Cannon 示例
    • 字符映射示例
    • Classwizard 示例
    • examples/widgets/graphicsview/collidingmice
    • 同心圆示例
    • examples/widgets/graphicsview/diagramscene
    • 数字时钟示例
    • 目录视图示例
    • Dock Widget 示例
    • examples/widgets/graphicsview/dragdroprobot
    • examples/widgets/draganddrop/draggabletext
    • Drop Site Example
    • 动态布局示例
    • Easing Example
    • 可编辑树模型示例
    • examples/widgets/graphicsview/elasticnodes
    • examples/widgets/dialogs/extension
    • examples/widgets/itemviews/fetchmore
    • 流式布局示例
    • GNU gettext 示例
    • examples/widgets/imageviewer
    • JSON 模型示例
    • 许可证向导示例
    • examples/widgets/effects/lighting
    • Qt Linguist 示例
    • examples/widgets/mainwindows/mdi
    • 模型视图教程示例
    • examples/widgets/richtext/orderform
    • Painter Example
    • 绘图示例
    • QRegularExpression 示例
    • Screenshot Example
    • 简单的RHI小部件示例
    • SpinBox 委托示例
    • examples/widgets/dialogs/standarddialogs
    • Star Delegate Example
    • 状态示例
    • Syntax Highlighter Example
    • examples/widgets/desktop/systray
    • 选项卡对话框示例
    • Tetrix
    • TextEdit 示例
    • TextObject 示例
    • examples/widgets/thread_signals
    • examples/widgets/dialogs/trivialwizard
    • 任务菜单扩展示例
    • examples/uitools/uiloader
    • MIME类型浏览器示例
    • 设置编辑器示例
    • examples/corelib/ipc/sharedmemory
    • Mandelbrot 线程示例
    • Async “Eratosthenes” 示例
    • Async “Minimal” Example
    • examples/network/blockingfortuneclient
    • 下载器示例
    • examples/network/fortuneclient
    • examples/network/fortuneserver
    • Google 建议示例
    • Loopback 示例
    • examples/network/threadedfortuneserver
    • SQL Books Example
    • examples/dbus/listnames
    • examples/dbus/pingpong
    • DOM 书签示例
    • 模拟时钟窗口示例
    • RHI 窗口示例
    • 上下文信息示例
    • 你好 GL2 示例
    • 纹理示例
    • Threaded QOpenGLWidget 示例
    • Sample Bindings Example
    • 使用CMake
    • 可脚本化应用程序示例
    • WigglyWidget 示例
    • 媒体播放器示例
    • RESTful API client
    • 文档查看器示例
    • OSM Buildings
    • Simple HTTP Server Example
    • Widget Graph Gallery
    • 简单条形图
    • HelloGraphs 示例
    • 最小曲面示例
    • Graph Gallery
    • 曲面图库
    • Bars 3D 示例
    • Surface 示例
    • Surface 示例
    • Surface 示例
    • 区域图示例
    • 音频示例
    • 柱状图示例
    • Callout Example
    • 图表主题示例
    • Donut Chart Breakdown Example
    • 动态样条示例
    • Legend Example
    • 折线和柱状图示例
    • 折线图示例
    • 对数轴示例
    • 内存使用示例
    • 模型数据示例
    • 嵌套甜甜圈示例
    • 百分比条形图示例
    • 饼图示例
    • Selected Point Configuration Example
    • Light Markers and Points Selection Example
    • QML 极坐标图示例
    • 温度记录示例
    • 缩放折线图示例
    • 音频输出示例
    • 音频源示例
    • 相机示例
    • Player Example
    • 屏幕捕获示例
    • Nano 浏览器示例
    • examples/webenginewidgets/markdowneditor
    • WebEngine 通知示例
    • Simple Browser
    • Qt Widgets Nano 浏览器示例
    • Ax Viewer 示例
    • 蓝牙扫描仪示例
    • 蓝牙低功耗心率游戏
    • 蓝牙低功耗心率服务器
    • Bluetooth Low Energy Scanner Example
    • Networkx 查看器示例
    • OpenCV 人脸检测示例
    • Pandas 简单示例
    • Scikit Image 示例
    • Matplotlib Widget 3D 示例
    • Matplotlib Widget 高斯示例
    • 地图查看器示例
    • Reddit 示例
    • PDF 查看器示例
    • PDF 查看器示例
    • 自定义几何示例
    • Qt Quick 3D 介绍示例
    • Procedural Texture Example
    • examples/remoteobjects/modelview
    • Spatial Audio Panning Example
    • Hello Speak
    • 简单的Qt 3D示例
    • CAN总线示例
    • Modbus Client 示例
    • 终端示例
    • 移动块示例
    • examples/statemachine/ping_pong
    • examples/statemachine/rogue
    • 交通灯示例
    • WebChannel 独立示例
    • Simple CoAP Client Example
    • Simple MQTT Client Example
    • Qt OPC UA 查看器示例
    • 财务经理示例 - 第1部分
    • 财务经理示例 - 第2部分
    • 财务经理示例 - 第3部分
    • Minibrowser 示例
  • 视频
  • 部署
  • 注意事项
  • 开发者笔记
  • 发布说明
  • 模块索引
Back to top

小部件库示例¶

Qt 对小部件样式和主题的支持使您的应用程序能够适应本地桌面环境。

小部件示例展示了当配置为使用特定样式时,Qt 中可用的一些小部件可能的外观。每种样式仅在相应的平台上可用,并通过集成到平台主题中提供原生的外观和感觉。因此,最终的外观会根据当前活动的主题而有所不同。

Widgets Gallery Screenshot

下载 这个 示例

# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
from __future__ import annotations

"""PySide6 port of the widgets/gallery example from Qt v5.15"""

import sys

from PySide6.QtWidgets import QApplication
from widgetgallery import WidgetGallery


if __name__ == '__main__':
    app = QApplication()
    gallery = WidgetGallery()
    gallery.show()
    sys.exit(app.exec())
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
from __future__ import annotations

import sys

from PySide6.QtCore import (QDateTime, QDir, QLibraryInfo, QSysInfo, Qt,
                            QTimer, Slot, qVersion)
from PySide6.QtGui import (QCursor, QDesktopServices, QGuiApplication, QIcon,
                           QKeySequence, QShortcut, QStandardItem,
                           QStandardItemModel)
from PySide6.QtWidgets import (QApplication, QCheckBox, QComboBox,
                               QCommandLinkButton, QDateTimeEdit, QDial,
                               QDialog, QDialogButtonBox, QFileSystemModel,
                               QGridLayout, QGroupBox, QHBoxLayout, QLabel,
                               QLineEdit, QListView, QMenu, QPlainTextEdit,
                               QProgressBar, QPushButton, QRadioButton,
                               QScrollBar, QSizePolicy, QSlider, QSpinBox,
                               QStyleFactory, QTableWidget, QTabWidget,
                               QTextBrowser, QTextEdit, QToolBox, QToolButton,
                               QTreeView, QVBoxLayout, QWidget)

POEM = """Twinkle, twinkle, little star,
How I wonder what you are.
Up above the world so high,
Like a diamond in the sky.
Twinkle, twinkle, little star,
How I wonder what you arenot"""

DIR_OPEN_ICON = ":/qt-project.org/styles/commonstyle/images/diropen-128.png"

COMPUTER_ICON = ":/qt-project.org/styles/commonstyle/images/computer-32.png"

SYSTEMINFO = """<html><head/><body>
<h3>Python</h3><p>{}</p>
<h3>Qt Build</h3><p>{}</p>
<h3>Operating System</h3><p>{}</p>
<h3>Screens</h3>
{}
</body></html>"""


def class_name(o):
    return o.metaObject().className()


def help_url(page):
    """Build a Qt help URL from the page name"""
    major_version = qVersion().split('.')[0]
    return f"https://doc.qt.io/qt-{major_version}/{page}.html"


def launch_help(widget):
    """Launch a widget's help page"""
    url = help_url(class_name(widget).lower())
    QDesktopServices.openUrl(url)


def launch_module_help():
    QDesktopServices.openUrl(help_url("qtwidgets-index"))


def init_widget(w, name):
    """Init a widget for the gallery, give it a tooltip showing the
       class name"""
    w.setObjectName(name)
    w.setToolTip(class_name(w))


def style_names():
    """Return a list of styles, default platform style first"""
    default_style_name = QApplication.style().objectName().lower()
    result = []
    for style in QStyleFactory.keys():
        if style.lower() == default_style_name:
            result.insert(0, style)
        else:
            result.append(style)
    return result


def embed_into_hbox_layout(w, margin=5):
    """Embed a widget into a layout to give it a frame"""
    result = QWidget()
    layout = QHBoxLayout(result)
    layout.setContentsMargins(margin, margin, margin, margin)
    layout.addWidget(w)
    return result


def format_geometry(rect):
    """Format a geometry as a X11 geometry specification"""
    w = rect.width()
    h = rect.height()
    x = rect.x()
    y = rect.y()
    return f"{w}x{h}{x:+d}{y:+d}"


def screen_info(widget):
    """Format information on the screens"""
    policy = QGuiApplication.highDpiScaleFactorRoundingPolicy()
    policy_string = str(policy).split('.')[-1]
    result = f"<p>High DPI scale factor rounding policy: {policy_string}</p><ol>"
    for screen in QGuiApplication.screens():
        current = screen == widget.screen()
        result += "<li>"
        if current:
            result += "<i>"
        name = screen.name()
        geometry = format_geometry(screen.geometry())
        dpi = int(screen.logicalDotsPerInchX())
        dpr = screen.devicePixelRatio()
        result += f'"{name}" {geometry} {dpi}DPI, DPR={dpr}'
        if current:
            result += "</i>"
        result += "</li>"
    result += "</ol>"
    return result


class WidgetGallery(QDialog):
    """Dialog displaying a gallery of Qt Widgets"""

    def __init__(self):
        super().__init__()

        self.setWindowIcon(QIcon(':/qt-project.org/logos/pysidelogo.png'))
        self._progress_bar = self.create_progress_bar()

        self._style_combobox = QComboBox()
        init_widget(self._style_combobox, "styleComboBox")
        self._style_combobox.addItems(style_names())

        style_label = QLabel("Style:")
        init_widget(style_label, "style_label")
        style_label.setBuddy(self._style_combobox)

        help_label = QLabel("Press F1 over a widget to see Documentation")
        init_widget(help_label, "help_label")

        disable_widgets_checkbox = QCheckBox("Disable widgets")
        init_widget(disable_widgets_checkbox, "disable_widgets_checkbox")

        buttons_groupbox = self.create_buttons_groupbox()
        itemview_tabwidget = self.create_itemview_tabwidget()
        simple_input_widgets_groupbox = self.create_simple_inputwidgets_groupbox()
        text_toolbox = self.create_text_toolbox()

        self._style_combobox.textActivated.connect(self.change_style)
        disable_widgets_checkbox.toggled.connect(buttons_groupbox.setDisabled)
        disable_widgets_checkbox.toggled.connect(text_toolbox.setDisabled)
        disable_widgets_checkbox.toggled.connect(itemview_tabwidget.setDisabled)
        disable_widgets_checkbox.toggled.connect(simple_input_widgets_groupbox.setDisabled)

        help_shortcut = QShortcut(self)
        help_shortcut.setKey(QKeySequence.HelpContents)
        help_shortcut.activated.connect(self.help_on_current_widget)

        top_layout = QHBoxLayout()
        top_layout.addWidget(style_label)
        top_layout.addWidget(self._style_combobox)
        top_layout.addStretch(1)
        top_layout.addWidget(help_label)
        top_layout.addStretch(1)
        top_layout.addWidget(disable_widgets_checkbox)

        dialog_buttonbox = QDialogButtonBox(QDialogButtonBox.Help
                                            | QDialogButtonBox.Close)
        init_widget(dialog_buttonbox, "dialogButtonBox")
        dialog_buttonbox.helpRequested.connect(launch_module_help)
        dialog_buttonbox.rejected.connect(self.reject)

        main_layout = QGridLayout(self)
        main_layout.addLayout(top_layout, 0, 0, 1, 2)
        main_layout.addWidget(buttons_groupbox, 1, 0)
        main_layout.addWidget(simple_input_widgets_groupbox, 1, 1)
        main_layout.addWidget(itemview_tabwidget, 2, 0)
        main_layout.addWidget(text_toolbox, 2, 1)
        main_layout.addWidget(self._progress_bar, 3, 0, 1, 2)
        main_layout.addWidget(dialog_buttonbox, 4, 0, 1, 2)

        qv = qVersion()
        self.setWindowTitle(f"Widget Gallery Qt {qv}")

    def setVisible(self, visible):
        super(WidgetGallery, self).setVisible(visible)
        if visible:
            self.windowHandle().screenChanged.connect(self.update_systeminfo)
            self.update_systeminfo()

    @Slot(str)
    def change_style(self, style_name):
        QApplication.setStyle(QStyleFactory.create(style_name))

    @Slot()
    def advance_progressbar(self):
        cur_val = self._progress_bar.value()
        max_val = self._progress_bar.maximum()
        self._progress_bar.setValue(cur_val + (max_val - cur_val) / 100)

    def create_buttons_groupbox(self):
        result = QGroupBox("Buttons")
        init_widget(result, "buttons_groupbox")

        default_pushbutton = QPushButton("Default Push Button")
        init_widget(default_pushbutton, "default_pushbutton")
        default_pushbutton.setDefault(True)

        toggle_pushbutton = QPushButton("Toggle Push Button")
        init_widget(toggle_pushbutton, "toggle_pushbutton")
        toggle_pushbutton.setCheckable(True)
        toggle_pushbutton.setChecked(True)

        flat_pushbutton = QPushButton("Flat Push Button")
        init_widget(flat_pushbutton, "flat_pushbutton")
        flat_pushbutton.setFlat(True)

        toolbutton = QToolButton()
        init_widget(toolbutton, "toolButton")
        toolbutton.setText("Tool Button")

        menu_toolbutton = QToolButton()
        init_widget(menu_toolbutton, "menuButton")
        menu_toolbutton.setText("Menu Button")
        tool_menu = QMenu(menu_toolbutton)
        menu_toolbutton.setPopupMode(QToolButton.InstantPopup)
        tool_menu.addAction("Option")
        tool_menu.addSeparator()
        action = tool_menu.addAction("Checkable Option")
        action.setCheckable(True)
        menu_toolbutton.setMenu(tool_menu)
        tool_layout = QHBoxLayout()
        tool_layout.addWidget(toolbutton)
        tool_layout.addWidget(menu_toolbutton)

        commandlinkbutton = QCommandLinkButton("Command Link Button")
        init_widget(commandlinkbutton, "commandLinkButton")
        commandlinkbutton.setDescription("Description")

        button_layout = QVBoxLayout()
        button_layout.addWidget(default_pushbutton)
        button_layout.addWidget(toggle_pushbutton)
        button_layout.addWidget(flat_pushbutton)
        button_layout.addLayout(tool_layout)
        button_layout.addWidget(commandlinkbutton)
        button_layout.addStretch(1)

        radiobutton_1 = QRadioButton("Radio button 1")
        init_widget(radiobutton_1, "radioButton1")
        radiobutton_2 = QRadioButton("Radio button 2")
        init_widget(radiobutton_2, "radioButton2")
        radiobutton_3 = QRadioButton("Radio button 3")
        init_widget(radiobutton_3, "radioButton3")
        radiobutton_1.setChecked(True)

        checkbox = QCheckBox("Tri-state check box")
        init_widget(checkbox, "checkBox")
        checkbox.setTristate(True)
        checkbox.setCheckState(Qt.PartiallyChecked)

        checkable_layout = QVBoxLayout()
        checkable_layout.addWidget(radiobutton_1)
        checkable_layout.addWidget(radiobutton_2)
        checkable_layout.addWidget(radiobutton_3)
        checkable_layout.addWidget(checkbox)
        checkable_layout.addStretch(1)

        main_layout = QHBoxLayout(result)
        main_layout.addLayout(button_layout)
        main_layout.addLayout(checkable_layout)
        main_layout.addStretch()
        return result

    def create_text_toolbox(self):
        result = QToolBox()
        init_widget(result, "toolBox")

        # Create centered/italic HTML rich text
        rich_text = "<html><head/><body><i>"
        for line in POEM.split('\n'):
            rich_text += f"<center>{line}</center>"
        rich_text += "</i></body></html>"

        text_edit = QTextEdit(rich_text)
        init_widget(text_edit, "textEdit")
        plain_textedit = QPlainTextEdit(POEM)
        init_widget(plain_textedit, "plainTextEdit")

        self._systeminfo_textbrowser = QTextBrowser()
        init_widget(self._systeminfo_textbrowser, "systemInfoTextBrowser")

        result.addItem(embed_into_hbox_layout(text_edit), "Text Edit")
        result.addItem(embed_into_hbox_layout(plain_textedit),
                       "Plain Text Edit")
        result.addItem(embed_into_hbox_layout(self._systeminfo_textbrowser),
                       "Text Browser")
        return result

    def create_itemview_tabwidget(self):
        result = QTabWidget()
        init_widget(result, "bottomLeftTabWidget")
        result.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Ignored)

        tree_view = QTreeView()
        init_widget(tree_view, "treeView")
        filesystem_model = QFileSystemModel(tree_view)
        filesystem_model.setRootPath(QDir.rootPath())
        tree_view.setModel(filesystem_model)

        table_widget = QTableWidget()
        init_widget(table_widget, "tableWidget")
        table_widget.setRowCount(10)
        table_widget.setColumnCount(10)

        list_model = QStandardItemModel(0, 1, result)

        list_model.appendRow(QStandardItem(QIcon(DIR_OPEN_ICON), "Directory"))
        list_model.appendRow(QStandardItem(QIcon(COMPUTER_ICON), "Computer"))

        list_view = QListView()
        init_widget(list_view, "listView")
        list_view.setModel(list_model)

        icon_mode_listview = QListView()
        init_widget(icon_mode_listview, "iconModeListView")

        icon_mode_listview.setViewMode(QListView.IconMode)
        icon_mode_listview.setModel(list_model)

        result.addTab(embed_into_hbox_layout(tree_view), "Tree View")
        result.addTab(embed_into_hbox_layout(table_widget), "Table")
        result.addTab(embed_into_hbox_layout(list_view), "List")
        result.addTab(embed_into_hbox_layout(icon_mode_listview),
                      "Icon Mode List")
        return result

    def create_simple_inputwidgets_groupbox(self):
        result = QGroupBox("Simple Input Widgets")
        init_widget(result, "bottomRightGroupBox")
        result.setCheckable(True)
        result.setChecked(True)

        lineedit = QLineEdit("s3cRe7")
        init_widget(lineedit, "lineEdit")
        lineedit.setClearButtonEnabled(True)
        lineedit.setEchoMode(QLineEdit.Password)

        spin_box = QSpinBox()
        init_widget(spin_box, "spinBox")
        spin_box.setValue(50)

        date_timeedit = QDateTimeEdit()
        init_widget(date_timeedit, "dateTimeEdit")
        date_timeedit.setDateTime(QDateTime.currentDateTime())

        slider = QSlider()
        init_widget(slider, "slider")
        slider.setOrientation(Qt.Orientation.Horizontal)
        slider.setValue(40)

        scrollbar = QScrollBar()
        init_widget(scrollbar, "scrollBar")
        scrollbar.setOrientation(Qt.Orientation.Horizontal)
        scrollbar.setValue(60)

        dial = QDial()
        init_widget(dial, "dial")
        dial.setValue(30)
        dial.setNotchesVisible(True)

        layout = QGridLayout(result)
        layout.addWidget(lineedit, 0, 0, 1, 2)
        layout.addWidget(spin_box, 1, 0, 1, 2)
        layout.addWidget(date_timeedit, 2, 0, 1, 2)
        layout.addWidget(slider, 3, 0)
        layout.addWidget(scrollbar, 4, 0)
        layout.addWidget(dial, 3, 1, 2, 1)
        layout.setRowStretch(5, 1)
        return result

    def create_progress_bar(self):
        result = QProgressBar()
        init_widget(result, "progressBar")
        result.setRange(0, 10000)
        result.setValue(0)

        timer = QTimer(self)
        timer.timeout.connect(self.advance_progressbar)
        timer.start(1000)
        return result

    @Slot()
    def update_systeminfo(self):
        """Display system information"""
        system_info = SYSTEMINFO.format(sys.version,
                                        QLibraryInfo.build(),
                                        QSysInfo.prettyProductName(),
                                        screen_info(self))
        self._systeminfo_textbrowser.setHtml(system_info)

    @Slot()
    def help_on_current_widget(self):
        """Display help on widget under mouse"""
        w = QApplication.widgetAt(QCursor.pos(self.screen()))
        while w:  # Skip over internal widgets
            name = w.objectName()
            if name and not name.startswith("qt_"):
                launch_help(w)
                break
            w = w.parentWidget()
Next
Address Book Example
Previous
Qt Quick Controls - Filesystem Explorer