QML Hello World 入门示例

0 阅读2分钟

本文实现一个带动画效果的 Hello World:程序启动后,"Hello World" 文字从窗口顶部弹跳到中间,同时颜色从白色渐变到深灰色,整个动画持续 2 秒。

helloworld.gif

通过这个 demo,读者可以掌握 Qt Quick 中 NumberAnimationColorAnimation 两种基础动画组件的使用方法,以及 Component.onCompleted 信号的触发时机。

完整可复用代码

在 Qt Creator 中创建 Qt Quick Application 项目,将 main.qml 文件内容替换为以下代码:

import QtQuick
import QtQuick.Window

Window {
    id: root
    width: 400
    height: 300
    visible: true
    color: "#fff"
    title: "QML —— Hello World"

    Text {
        id: helloText
        text: "Hello World"
        color: "#fff"
        font.pixelSize: 48
        font.bold: true
        anchors.horizontalCenter: parent.horizontalCenter
        y: 0

        ColorAnimation {
            id: colorAnim
            target: helloText
            property: "color"
            from: "#fff"
            to: "#333"
            duration: 2000
        }

        NumberAnimation {
            id: bounceAnim
            target: helloText
            property: "y"
            from: 0
            to: (root.height - helloText.height) / 2
            duration: 2000
        }

        Component.onCompleted: {
            bounceAnim.start()
            colorAnim.start()
        }
    }
}

关键逻辑解析

这段代码的核心逻辑分为三个部分:

1. 窗口与文本基础设置

Window {
    id: root
    width: 400
    height: 300
    visible: true
    color: "#fff"
    title: "QML —— Hello World"
}

Window 是 QML 的顶层窗口组件,visible: true 让窗口显示,color: "#fff" 设置白色背景。

Text {
    id: helloText
    text: "Hello World"
    color: "#fff"
    font.pixelSize: 48
    font.bold: true
    anchors.horizontalCenter: parent.horizontalCenter
    y: 0
}

文本初始颜色设为白色(与背景相同),所以启动时文字是"看不见"的。y: 0 让文字位于窗口顶部。

2. 两种动画效果

颜色动画:让文字从白色渐变到深灰色

ColorAnimation {
    id: colorAnim
    target: helloText
    property: "color"
    from: "#fff"
    to: "#333"
    duration: 2000
}

位移动画:让文字从顶部移动到垂直居中位置

NumberAnimation {
    id: bounceAnim
    target: helloText
    property: "y"
    from: 0
    to: (root.height - helloText.height) / 2
    duration: 2000
}

两个动画的 duration 都是 2000 毫秒,同步执行产生组合效果。

3. 组件加载完成后启动动画

Component.onCompleted: {
    bounceAnim.start()
    colorAnim.start()
}

Component.onCompleted 在组件加载完成后自动触发,在这里同时启动两个动画。

运行验证

打开 Qt Creator,点击打开项目,找到 qml_hello 示例的 CMakeLists.txt 文件;

image.png

image.png

点击左下角绿色三角形"运行"按钮,或按 Ctrl+R

image.png

观察窗口:文字从顶部弹跳到中间,同时颜色从白色渐变到深灰色

helloworld.gif

扩展复用方向

读者可以直接复用这段动画逻辑,或基于此扩展更丰富的效果:

  • 添加交互:在 Text 外层包裹 MouseArea,点击时重新播放动画
  • 替换动画类型:将 NumberAnimation 替换为 RotationAnimation,实现旋转效果
  • 组合多个动画:使用 ParallelAnimationSequentialAnimation 组合更多动画
  • 结合状态机:使用 StateTransition 实现更复杂的交互状态切换
// 点击重新播放动画的示例
MouseArea {
    anchors.fill: parent
    onClicked: {
        bounceAnim.restart()
        colorAnim.restart()
    }
}

已验证环境