LinearGradient 是 QML 中用于创建线性渐变效果的元素,它可以为矩形、文本或其他可视元素添加平滑的颜色过渡效果。
基本用法
qml
import QtQuick 2.15
Rectangle {
width: 200
height: 200
gradient: LinearGradient {
start: Qt.point(0, 0) // 渐变起点
end: Qt.point(200, 200) // 渐变终点
// 定义渐变颜色停靠点
GradientStop { position: 0.0; color: "red" }
GradientStop { position: 0.5; color: "yellow" }
GradientStop { position: 1.0; color: "green" }
}
}
主要属性
-
start 和 end:
-
定义渐变的方向线
-
使用 Qt.point(x, y) 指定坐标
-
默认是 start(0,0) 到 end(0, height) 的垂直渐变
-
-
GradientStop:
-
position
: 0.0 到 1.0 之间的值,表示在渐变线上的位置 -
color
: 该位置的颜色
-
常见渐变方向示例
水平渐变
qml
gradient: LinearGradient {
start: Qt.point(0, 0)
end: Qt.point(width, 0)
// 颜色定义...
}
垂直渐变
qml
gradient: LinearGradient {
start: Qt.point(0, 0)
end: Qt.point(0, height)
// 颜色定义...
}
对角线渐变
qml
gradient: LinearGradient {
start: Qt.point(0, 0)
end: Qt.point(width, height)
// 颜色定义...
}
实际应用示例
qml
import QtQuick 2.15
Item {
width: 400
height: 400
// 带渐变的按钮
Rectangle {
id: button
width: 150
height: 50
radius: 5
anchors.centerIn: parent
gradient: LinearGradient {
start: Qt.point(0, 0)
end: Qt.point(0, button.height)
GradientStop { position: 0.0; color: "#4a6da7" }
GradientStop { position: 1.0; color: "#1e3a6a" }
}
Text {
text: "点击我"
color: "white"
anchors.centerIn: parent
font.pixelSize: 16
}
}
// 带渐变的文本
Text {
y: 100
width: parent.width
horizontalAlignment: Text.AlignHCenter
text: "渐变文字"
font.pixelSize: 48
LinearGradient {
anchors.fill: parent
start: Qt.point(0, 0)
end: Qt.point(parent.width, 0)
GradientStop { position: 0.0; color: "red" }
GradientStop { position: 0.5; color: "yellow" }
GradientStop { position: 1.0; color: "blue" }
}
}
}
注意事项
-
LinearGradient 通常作为其他元素的 gradient 属性使用
-
可以创建多个颜色停靠点来实现复杂的渐变效果
-
渐变效果在性能上比纯色渲染开销稍大,但现代硬件上通常不是问题
-
对于简单的两种颜色渐变,也可以考虑使用 Rectangle 的 gradient 属性直接定义