在 QML 中的组件上添加动态行为

问题描述 投票:0回答:1

最近我想在 QML 中的 js 函数中添加行为,但我不知道如何! 例如,我该如何做到这一点:

    Behavior on color{ 
        id:behavior
        enabled:false;
        ColorAnimation {}
    }
    Rectangle{
        id:rect 
        Component.onCompleted: rect.setBehavior = behavior; // it's wrong expression 
    }

我只需要一些API,比如顶部错误表达式,存在吗?

我也尝试了底部代码但无法工作:

我也可以尝试下面的代码:

   Component.onCompleted: behavior.enabled = true; 

因为我想在创建矩形时阻止工作行为并在完成后启用它,但它无法正常工作!

但是当我在特定条件下有很多行为时,我只想使用一行代码来更改(例如) Color 上的行为,例如:

Component.setNewBehaviorOnColor(specificBehaviorOnColorID);

qml qt5 behavior
1个回答
0
投票

您可以考虑使用

Instantiator
+
PropertyAnimation
代替
Behavior

通过这种方式,你的 Javascript 代码只会设置

Instantiator
model
。这样,您就可以通过设置或清除
model
属性来启动/停止任何您想要的动画:

import QtQuick
import QtQuick.Controls
Page {
    id: page

    title: "Instantiator + PropertyAnimation"

    Rectangle {
        id: rect
        x: 100; y: 100; width: 100; height: 100
        color: "red"
    }
    
    Instantiator {
        id: instantiator
        model: 0
        PropertyAnimation {
            target: rect
            property: modelData[0]
            to: modelData[1]
            duration: 500
            Component.onCompleted: start()
        }
    }
    
    MouseArea {
        anchors.fill: parent
        onClicked: {
            instantiator.model = [
                ["x",Math.random()*page.width],
                ["y",Math.random()*page.height],
                ["width",Math.random()*200],
                ["height",Math.random()*200],
                ["color",Qt.rgba(
                    Math.random(),
                    Math.random(),
                    Math.random(),
                    1)]
            ]
        }
    }
}

您可以在线尝试!

© www.soinside.com 2019 - 2024. All rights reserved.