是否可以在QML中将颜色渐变应用于文本?

jne*_*der 6 qt gradient styling qml

是否可以在QML中将颜色渐变应用于文本?如果是这样,怎么样?如果没有,那么达到同样效果的可接受手段是什么?

Mee*_*fte 10

您可以使用LinearGradient QML Type.

import QtQuick 2.4
import QtQuick.Window 2.2
import QtGraphicalEffects 1.0

Window
{
    visible: true
    height: 500
    width: 500
    Text {
        id: text
        font.pointSize: 55
        anchors.centerIn: parent
        text: "Hello World!"
        visible: false
    }
    LinearGradient  {
        anchors.fill: text
        source: text
        gradient: Gradient {
            GradientStop { position: 0; color: "yellow" }
            GradientStop { position: 1; color: "red" }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 同意@BaCaRoZzo,此解决方案更简单,更可取 (2认同)

fol*_*bis 6

可以使用Item层 例如:

import QtQuick 2.3
import QtQuick.Window 2.0
import QtGraphicalEffects 1.0

Window {
    width: 400
    height: 300
    visible: true
    Rectangle {
        id: gradientRect;
        width: 10
        height: 10
        gradient: Gradient {
            GradientStop { position: 0; color: "yellow" }
            GradientStop { position: 1; color: "red" }
        }
        visible: false;
        layer.enabled: true;
        layer.smooth: true
    }

    Text {
        id: txt
        anchors.centerIn: parent
        text: "Hello, world"
        font.pixelSize: 64
        layer.enabled: true
        layer.samplerName: "maskSource"
        layer.effect: ShaderEffect {
            property var colorSource: gradientRect;
            fragmentShader: "
                        uniform lowp sampler2D colorSource;
                        uniform lowp sampler2D maskSource;
                        uniform lowp float qt_Opacity;
                        varying highp vec2 qt_TexCoord0;
                        void main() {
                            gl_FragColor =
                                texture2D(colorSource, qt_TexCoord0)
                                * texture2D(maskSource, qt_TexCoord0).a
                                * qt_Opacity;
                        }
                    "
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这里查看更多示例.