Contents - Qt 框架 Menu - Qt 框架 Expand - Qt 框架 Light mode - Qt 框架 Dark mode - Qt 框架 Auto light/dark mode - Qt 框架
Python for Qt
Logo
Python for Qt
  • 快速入门
  • 商业用途
  • 开始使用
  • 模块API
  • 工具
  • 教程
  • 示例
    • 扩展QML - 添加类型示例
    • 高级扩展QML - BirthdayParty基础项目
    • 高级扩展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
    • 文本属性示例
    • 使用模型示例
    • 对象列表模型示例
    • QML Squircle下的OpenGL
    • 场景图绘制项示例
    • QQuickRenderControl OpenGL示例
    • 场景图 - 自定义几何形状
    • 字符串列表模型示例
    • Qt Quick示例 - 窗口和屏幕
    • Qt Quick控件2 - 画廊
    • Qt Quick控件 - 联系人列表
    • Qt Quick控件 - 文件系统资源管理器
    • 小部件画廊示例
    • 通讯录示例
    • 通讯录示例
    • examples/widgets/graphicsview/anchorlayout
    • 动画拼图示例
    • 应用程序选择器示例
    • examples/widgets/mainwindows/application
    • 基本绘图示例
    • examples/widgets/itemviews/basicfiltermodel
    • 基本布局示例
    • 模糊选择器效果示例
    • 边框布局示例
    • 炮塔示例
    • 字符映射表示例
    • 类向导示例
    • examples/widgets/graphicsview/collidingmice
    • 同心圆示例
    • examples/widgets/graphicsview/diagramscene
    • 数字时钟示例
    • 目录视图示例
    • 浮动小部件示例
    • examples/widgets/graphicsview/dragdroprobot
    • examples/widgets/draganddrop/draggabletext
    • 放置区域示例
    • 动态布局示例
    • 缓动示例
    • 可编辑树模型示例
    • 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
    • 绘图示例
    • 绘图示例
    • QRegularExpression示例
    • 截图示例
    • 简单RHI小部件示例
    • 自旋框代理示例
    • examples/widgets/dialogs/standarddialogs
    • 星代理示例
    • 状态示例
    • 语法高亮示例
    • examples/widgets/desktop/systray
    • 标签对话框示例
    • 俄罗斯方块
    • 文本编辑器示例
    • 文本对象示例
    • examples/widgets/thread_signals
    • examples/widgets/dialogs/trivialwizard
    • 任务菜单扩展示例
    • examples/uitools/uiloader
    • MIME类型浏览器示例
    • 设置编辑器示例
    • examples/corelib/ipc/sharedmemory
    • Mandelbrot线程示例
    • 异步“埃拉托斯特尼”示例
    • 异步“最小”示例
    • examples/network/blockingfortuneclient
    • 下载器示例
    • examples/network/fortuneclient
    • examples/network/fortuneserver
    • Google 检索建议示例
    • 回环示例
    • examples/network/threadedfortuneserver
    • SQL 书籍示例
    • examples/dbus/listnames
    • examples/dbus/pingpong
    • DOM 书签示例
    • 模拟时钟窗口示例
    • RHI 窗口示例
    • 上下文信息示例
    • 你好 GL2 示例
    • 纹理示例
    • 线程 QOpenGLWidget 示例
    • 示例绑定示例
    • 使用 CMake
    • 可脚本应用程序示例
    • 波浪小部件示例
    • 媒体播放器示例
    • RESTful API 客户端
    • 文档查看器示例
    • 小部件画廊
    • 你好图表示例
    • 图形画廊
    • 表面图形画廊
    • 3D 条形示例
    • 表面示例
    • 表面示例
    • 表面示例
    • 面积图示例
    • 音频示例
    • 条形图示例
    • 引言示例
    • 图表主题示例
    • 圆形饼图细分示例
    • 动态样条图示例
    • 图例示例
    • 线形和条形图示例
    • 线形图示例
    • 对数轴示例
    • 内存使用示例
    • 模型数据示例
    • 嵌套饼图示例
    • 百分比条形图示例
    • 饼图示例
    • 选定点配置示例
    • 亮点和点选择示例
    • QML 极坐标图示例
    • 温度记录示例
    • 音频输出示例
    • 音频源示例
    • 相机示例
    • 播放器示例
    • 屏幕捕获示例
    • 纳诺浏览器示例
    • examples/webenginewidgets/markdowneditor
    • WebEngine 通知示例
    • 简单浏览器
    • Qt Widgets 纳诺浏览器示例
    • Ax 观察器示例
    • 蓝牙扫描仪示例
    • 蓝牙低能耗心率游戏
    • 蓝牙低能耗心率服务器
    • 蓝牙低能耗扫描仪示例
    • Networkx 观察器示例
    • OpenCV 人脸检测示例
    • Pandas 简单示例
    • Scikit 图像示例
    • Matplotlib 小部件 3D 示例
    • Matplotlib 小部件高斯示例
    • 地图查看器示例
    • Reddit 示例
    • PDF 查看器示例
    • PDF 查看器示例
    • 自定义几何形状示例
    • Qt Quick 3D 导入示例
    • 程序性纹理示例
    • examples/remoteobjects/modelview
    • 空间音频声像示例
    • 你好语音
    • 简单 Qt 3D 示例
    • CAN 总线示例
    • Modbus 客户端示例
    • 终端示例
    • 移动方块示例
    • examples/statemachine/ping_pong
    • examples/statemachine/rogue
    • 交通灯示例
    • WebChannel 独立示例
    • 简单 CoAP 客户端示例
    • 简单 MQTT 客户端示例
    • Qt OPC UA 观察器示例
  • 视频
  • 部署
  • 注意事项
  • 开发人员注意
  • 模块索引
回到顶部

小部件画廊示例#

Qt 对小部件样式和主题的支持,可以使您的应用程序与原生桌面环境搭配。

小部件示例显示当配置为使用特定样式时,Qt 中的一些小部件可能如何显示。每种样式仅在各自平台上可用,并通过集成到平台主题中提供本地样貌和感觉。因此,最终外观取决于活动主题。

Widgets Gallery Screenshot

下载 此 示例

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

"""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

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.ac.cn/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.Horizontal)
        slider.setValue(40)

        scrollbar = QScrollBar()
        init_widget(scrollbar, "scrollBar")
        scrollbar.setOrientation(Qt.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()
下一页
地址簿示例
上一页
Qt Quick 控件 - 文件系统浏览器
版权所有©2024 Qt公司有限公司。本文档中包含的文档贡献是相应所有者的版权。提供的文档许可证为GNU自由文档许可版1.3(https://gnu.ac.cn/licenses/fdl.html),该许可证由自由软件基金会发布。Qt及其相应标志是芬兰以及/或全世界Qt公司的商标。所有其他商标均为相应所有者的财产。
由Sphinx 和 @pradyunsg 的 Furo 制作