Behavior QML Type

定义属性更改的默认动画。更多

Import Statement: import QtQuick

属性

详细说明

行为定义了在特定属性值发生变化时应用的默认动画。

例如,下面的行为定义了每当Rectanglewidth 值发生变化时运行的NumberAnimation 。当点击MouseArea 时,width 将发生变化,从而触发该行为的动画:

import QtQuick

Rectangle {
    id: rect
    width: 100; height: 100
    color: "red"

    Behavior on width {
        NumberAnimation { duration: 1000 }
    }

    MouseArea {
        anchors.fill: parent
        onClicked: rect.width = 50
    }
}

请注意,一个属性不能有多个指定行为。要在一个行为中提供多个动画,请使用ParallelAnimationSequentialAnimation

如果状态变化的 Transition 与行为的属性相同,则Transition 动画会覆盖该状态变化的行为。有关使用行为为状态变化制作动画的一般建议,请参阅 Qt Quick Behaviors with States

另请参阅 Qt Quick 中的动画和转换行为示例Qt Qml.

属性文档

animation : Animation [default]

此属性表示行为触发时要运行的动画。


enabled : bool

当跟踪属性的值发生变化时,是否触发该行为。

默认情况下,行为已启用。


targetProperty group

targetProperty.name : string [read-only, since QtQuick 2.15]

targetProperty.object : QtObject [read-only, since QtQuick 2.15]

属性说明
名称此属性包含行为所控制属性的名称。
对象此属性包含此行为所控制属性的对象。

此属性可用于根据被控制属性的名称或对象定义自定义行为。

下面的示例定义了一个行为,当其控制的属性发生变化时,该行为会淡出和淡入其目标对象:

// FadeBehavior.qml
import QtQuick 2.15

Behavior {
    id: root
    property Item fadeTarget: targetProperty.object
    SequentialAnimation {
        NumberAnimation {
            target: root.fadeTarget
            property: "opacity"
            to: 0
            easing.type: Easing.InQuad
        }
        PropertyAction { } // actually change the controlled property between the 2 other animations
        NumberAnimation {
            target: root.fadeTarget
            property: "opacity"
            to: 1
            easing.type: Easing.OutQuad
        }
    }
}

当文本发生变化时,它可用于制作动画:

import QtQuick 2.15

Text {
    id: root
    property int counter
    text: counter
    FadeBehavior on text {}
    Timer {
        running: true
        repeat: true
        interval: 1000
        onTriggered: ++root.counter
    }
}

该 QML 属性在 QtQuick 2.15 中引入。


targetValue : Variant [read-only, since QtQuick 2.13]

该属性保存行为所控制属性的目标值。该值在动画开始前由行为设置。

此属性在 QtQuick 2.13 中引入。


© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.