Skip to content

1. QML 入门

1, QML 简介

QML(Qt Meta-Object Language)是一种基于 JavaScript 的声明式语言,用于描述用户界面元素及其交互行为。

要使用 QML 需要安装 Qt 完整的发行版本。

QML 是声明式 UI,而 Widget 是命令式 UI。声明式 UI 是面向功能的,能够通过绑定来自动更新。

Qt Quick 是 QML 的 UI 框架,它提供了一套用于创建动画、视觉效果、转换和过渡的元素。

2. 创建项目

安装 Qt 后,可以使用 Qt Creator 或者 Qt Design Studio 创建 QML 项目。本文以 Qt 6.6.0 为例。

QML 项目使用 .qmlproject 文件来管理项目,这个文件也是一个 QML 文件。

项目创建完成后,Qt 自动生成了一个 .qml 文件:

qml
import QtQuick

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")
    Text {
        anchors.centerIn: parent
        text: qsTr("Hello World")
    }
}

我们直接运行可以看到窗体,但是这个窗体并非此文件编译后的结果。而是运行了 qml 程序所渲染的结果。

我们使用一张图片填充背景:

qml
import QtQuick

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    Image {
        id: background
        anchors.fill: parent
        source: "./images/2023-12-06_13-09-39_6154.png"
    }
}

注意,最顶层的对象将先绘制。

下面我们再叠加一张图片,我们使用锚点属性 anchors 来定位。

qml
import QtQuick

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    Image {
        id: background
        anchors.fill: parent
        source: "./images/bg.png"

        Image {
            anchors.bottom: parent.bottom
            anchors.horizontalCenter: parent.horizontalCenter
            id: wheel
            source: "./images/test2.jpg"
        }
    }
}

下面我们实现点击选转图片:

qml
import QtQuick

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    Image {
        id: background
        anchors.fill: parent
        source: "./images/bg.png"

        Image {
            anchors.bottom: parent.bottom
            anchors.horizontalCenter: parent.horizontalCenter
            id: wheel
            source: "./images/test2.jpg"
        }

        MouseArea {
            anchors.fill: parent
            onClicked: wheel.rotation += 30
        }
    }
}

为了让动画更加流程,我们使用动画来过渡:

qml
import QtQuick

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    Image {
        id: background
        anchors.fill: parent
        source: "./images/bg.png"

        Image {
            anchors.bottom: parent.bottom
            anchors.horizontalCenter: parent.horizontalCenter
            id: wheel
            source: "./images/test2.jpg"

            Behavior on rotation {
                NumberAnimation {
                    duration: 100
                }
            }
        }

        MouseArea {
            anchors.fill: parent
            onClicked: wheel.rotation += 30
        }
    }
}