矩形内的 Qml 动画不起作用

Qml Animation inside Rectangle not working

存在第一个动画有效而第二个动画无效的问题。在第一种情况下,整个矩形都是动画的,这是不希望的,我只需要为标签设置动画,但是向标签添加动画并没有带来任何效果。你知道第二个动画没有动画的问题是什么吗?

第一个:

import QtQuick 2.12
import QtQuick.Layouts 1.12
import QtQuick.Controls 2.12
import QtQml.Models 2.12

Rectangle{
    property alias text: label.text
    clip: true
    NumberAnimation on x {
            id: animation
            from: 100.0
            to: -100.0
            duration: 500
            running: true//label.text.length > 25
            loops: Animation.Infinite
        }
    Label {
        anchors.fill : parent
        horizontalAlignment: Text.AlignHCenter;
        verticalAlignment: Text.AlignVCenter;
        id: label
    }
}

第二个:

import QtQuick 2.12
import QtQuick.Layouts 1.12
import QtQuick.Controls 2.12
import QtQml.Models 2.12

Rectangle{
    property alias text: label.text
    clip: true

    Label {
        anchors.fill : parent
        horizontalAlignment: Text.AlignHCenter;
        verticalAlignment: Text.AlignVCenter;
        id: label

        NumberAnimation on x {
            id: animation
            from: 100.0
            to: -100.0
            duration: 500
            running: true//label.text.length > 25
            loops: Animation.Infinite
        }

    }
}

我在你的第二个动画中发现了两个问题。

  1. 您的矩形应具有 宽度高度anchor.fill:父级

  2. 您应该删除标签 anchor.fill: parent 以允许更改 x

检查我的代码。现在正在运行:

import QtQuick 2.12
import QtQuick.Controls 2.12

Rectangle{
    property alias text: label.text
    clip: true
    anchors.fill: parent


    Label {
        horizontalAlignment: Text.AlignHCenter;
        verticalAlignment: Text.AlignVCenter;
        id: label
        Text {
            id: name
            text: qsTr("text")
            color: "black"
        }

        NumberAnimation on x {
            id: animation
            from: 100.0
            to: -100.0
            duration: 500
            running: true//label.text.length > 25
            loops: Animation.Infinite
        }

    }
}