在 QML 中,样式库(或 UI 框架)用于快速构建一致且美观的界面。Qt/QML 本身不提供内置的完整样式库,但可以通过以下方式实现样式管理或使用第三方库。
1. Qt Quick Controls 2 样式系统
Qt Quick Controls 2 是官方提供的 UI 组件库,支持多种样式(Style
)和主题(Theme
)。
1.1 内置样式
通过 QT_QUICK_CONTROLS_STYLE
环境变量或代码设置:
qml
import QtQuick.Controls 2.15
ApplicationWindow {
// 设置全局样式(必须在加载控件前设置)
Component.onCompleted: QtQuick.Controls.style = "Material" // 或 "Fusion", "Universal", "Windows"
Button {
text: "Styled Button"
}
}
支持的样式:
-
"Default"
:基础样式(轻量级,无特效)。 -
"Material"
:Google Material Design 风格(需QtQuick.Controls.Material
模块)。 -
"Fusion"
:跨平台桌面风格(类似 Qt Widgets)。 -
"Universal"
:微软 Fluent Design 风格(需QtQuick.Controls.Universal
模块)。 -
"Windows"
:Windows 原生风格(仅限 Windows 平台)。
1.2 自定义样式
通过覆盖控件的 delegate
或 style
属性:
qml
Button {
text: "Custom Button"
background: Rectangle {
color: "lightblue"
radius: 5
}
}
2. 第三方 QML 样式库
2.1 官方推荐扩展
-
Qt Quick Templates
提供无样式的控件模板,方便完全自定义(需手动实现样式逻辑)。
2.2 社区库
-
Neumorphism
仿新拟态风格(软阴影效果):qml
Rectangle { width: 200 height: 200 color: "#e0e5ec" radius: 20 layer.enabled: true layer.effect: DropShadow { color: "#ffffff" radius: 10 samples: 20 spread: 0.1 verticalOffset: -5 horizontalOffset: -5 } }
-
Qaterial
Material Design 的增强实现:GitHub - Qaterialqml
import Qaterial 1.0 Qaterial.Button { text: "Qaterial Button" icon.source: Qaterial.Icons.account }
-
QuickQanava
适用于图可视化(节点-连线类 UI):GitHub - QuickQanava
3. 纯 QML 样式管理
3.1 集中式样式变量
在根对象中定义全局样式属性:
qml
// Styles.qml
pragma Singleton
import QtQuick 2.0
QtObject {
property color primaryColor: "#6200ee"
property color secondaryColor: "#03dac6"
property int defaultMargin: 10
}
使用时通过 id
引用:
qml
import "Styles.qml" as Styles
Rectangle {
color: Styles.primaryColor
margin: Styles.defaultMargin
}
3.2 动态主题切换
结合 Loader
或 Qt.lighter()
/Qt.darker()
动态调整颜色:
qml
property bool darkMode: false
Rectangle {
color: darkMode ? Qt.darker("#6200ee", 1.5) : "#6200ee"
}
4. 实用工具
4.1 图标库
-
Qt 内置图标
使用QtQuick.Controls.Material
或Universal
的图标:qml
import QtQuick.Controls.Material 2.0 Button { icon.source: "qrc:/qt-project.org/imports/QtQuick/Controls/Material/images/check.svg" }
-
FontAwesome/Qaterial Icons
通过字体或 SVG 引入第三方图标。
4.2 动画效果
使用 Behavior
或 PropertyAnimation
增强交互:
qml
Button {
id: btn
background: Rectangle {
color: btn.pressed ? "lightgray" : "white"
Behavior on color { ColorAnimation { duration: 200 } }
}
}
5. 最佳实践
-
优先使用 Qt Quick Controls 2:对跨平台应用最友好。
-
避免硬编码样式:通过全局变量或配置文件管理颜色/尺寸。
-
性能优化:复杂样式(如阴影)启用
layer
时注意渲染开销。 -
响应式设计:结合
Screen
对象适配不同分辨率:qml
import QtQuick.Window 2.0 Text { font.pixelSize: Screen.width > 600 ? 18 : 12 }