16
社区成员




Timer {
id: timer2
interval:1000 // 每隔1秒触发一次
running: true // 启动定时器
repeat: true //重复触发
onTriggered: {
var animation = PropertyAnimation {
target: rect
property: ["x", "y"]
to: Qt.point(Math.random() * (parent.width - rect.width), Math.random() * (parent.height - rect.height))
duration:1000 // 动画持续时间为1秒
easing.type: Easing.InOutQuad // 缓动函数为InOutQuad
}
animation.start() // 启动属性动画
}
}
var animation = PropertyAnimation {
这段QML代码有什么问题呢?需要怎么修改呢?
对象不能在函数里直接创建,所以把对象放在外部:
Timer {
id: timer2
interval: 1000 // 每隔1秒触发一次
running: true // 启动定时器
repeat: true // 重复触发
onTriggered: {
animation.to = Qt.point(Math.random() * (parent.width - rect.width), Math.random() * (parent.height - rect.height))
animation.restart()
}
}
Rectangle {
id: rect // 添加目标元素的定义
width: 100
height: 100
color: "red"
}
PropertyAnimation {
id: animation
target: rect
property: ["x", "y"]
duration: 1000 // 动画持续时间为1秒
easing.type: Easing.InOutQuad
}
这段 QML 代码存在以下问题:
PropertyAnimation 是一个元素类型,而不是变量类型。它应该在元素声明的内部使用,而不是在变量声明的内部使用。因此,将 PropertyAnimation 移动到元素声明的内部。
rect 在代码中未定义,因此动画无法正确地找到目标。你需要确保在 target 属性中指定正确的目标元素。
修改后的代码如下:
Timer {
id: timer2
interval: 1000 // 每隔1秒触发一次
running: true // 启动定时器
repeat: true // 重复触发
onTriggered: {
var animation = PropertyAnimation {
target: rect // 修改为正确的目标元素
property: ["x", "y"]
to: Qt.point(Math.random() * (parent.width - rect.width), Math.random() * (parent.height - rect.height))
duration: 1000 // 动画持续时间为1秒
easing.type: Easing.InOutQuad // 缓动函数为InOutQuad
}
animation.start() // 启动属性动画
}
}
Rectangle {
id: rect // 添加目标元素的定义
width: 100
height: 100
color: "red"
}
请注意,这只是对原始代码的一种修正方法,具体修改取决于你想要实现的效果。