本页内容

Behavior QML Type

为属性变化定义默认动画。更多...

Import Statement: import QtQuick

属性

详细说明

“行为”用于定义当特定属性值发生变化时应应用的默认动画。

例如,以下“行为”定义了每当Rectangle 的width 值发生变化时,就会运行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
    }
}

请注意,一个属性不能被分配多个 Behavior。若要在一个 Behavior 中提供多个动画,请使用ParallelAnimation 或SequentialAnimation 。

Transition 如果状态变化具有与行为(Behavior)指向同一属性的状态变化动画(Transition ),则该状态变化动画将覆盖该状态变化对应的行为。有关使用行为(Behaviors)为状态变化添加动画的一般建议,请参阅《在Qt Quick 中将行为与状态结合使用》。

另请参阅 《Qt Quick 中的动画与过渡》、《Behavior示例》以及 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
    }
}

这些属性是在 QtQuick 2.15 中引入的。

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

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

该属性在 QtQuick 2.13 中引入。

© 2026 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.