本页内容

C

Qt Quick Ultralite 样式示例

演示如何在Qt Quick Ultralite中使用样式。

概述

本示例演示了如何定义和使用自定义的QtQuick.Controls 样式。相同的代码会被编译两次:一次作为styling_default (使用默认样式),另一次作为styling_custom (使用自定义样式)。样式之间的切换仅在项目的CMakeLists.txt 中进行。

有关自定义样式的更多信息,请参阅《控件样式设置》。

使用默认 QtQuick Controls 样式的样式示例,展示了标准的 Button 和 CheckBox 控件。

使用自定义样式的样式示例,展示了经过修改的 Button 和 CheckBox 控件。

项目结构

CMake 项目文件

CMakeLists.txt 文件定义了两个目标:

...
qul_add_target(styling_default QML_PROJECT styling_default.qmlproject GENERATE_ENTRYPOINT)
app_target_setup_os(styling_default)
...

第一个目标使用默认样式,并链接到Qul::Controls

...
# qul_add_target(styling_custom QML_PROJECT styling_custom.qmlproject GENERATE_ENTRYPOINT)
# app_target_setup_os(styling_custom)
...

而第二个目标(styling_custom )则使用styles/custom 目录中的样式。它链接到CustomControls ,该文件也被设置为MCU.Config.controlsStyle 的QmlProject属性。这两项操作通过其URI将默认样式切换为CustomControls 。

CustomControls 样式拥有自己的QmlProject文件:

        MCU.Module {
                uri: "CustomControls"
        }

        QmlFiles {
                files: ["Button.qml", "CheckBox.qml"]
        }

        ModuleFiles {
                MCU.qulModules: [
                        "Qul::ControlsTemplates",
        // This style links StyleDefault because one of the components is based
        // on a default style component. If it didn't depend on the default style
        // that would be unnecessary.
                        "Qul::Controls"
                ]
        }
}

该文件定义了 URI 为CustomControls 的CustomStyleLib ,仅因在CheckBox.qml 中被引用,才与Qul::Controls 建立关联。若CheckBox 是从零开始实现的,则无需链接此库。

默认样式

此styling.qml 文件使用了来自QtQuick.Controls 模块的 QML 类型。对于styling_default 目标,定义取自Qul::Controls 库;对于styling_custom 目标,则使用来自CustomStyleLib 的对象。

自定义样式

Button.qml 和CheckBox.qml 文件使用自定义样式重新实现了Button 和CheckBox 控件。

import QtQuick 2.15
import QtQuick.Controls.StyleDefault 1.0 as Base

Base.CheckBox {
    id: control

    indicator: Rectangle {
        x: control.leftPadding
        y: control.topPadding + (control.availableHeight - height) / 2
        width: control.availableHeight / 2
        height: control.availableHeight / 2
        radius: width / 2
        color: !control.enabled
            ? "gray"
            : (control.checked ? "green" : "red")
    }
}

例如,CheckBox 指示器与使用默认样式的CheckBox 控件有所不同。它采用了一种新的圆形指示器。

文件:

在某些 Qt 许可证下可用。
了解更多。