Qt5.9.3商业版:如何无需QML函数声明式更新QQuickItem坐标
Hey there! Let's solve this with pure declarative QML—no functions or global properties required, perfect for your Qt 5.9.3 commercial setup. Here's a straightforward approach that works exactly as you need:
Core Idea
We'll use QML States and Transitions to handle the movement declaratively. The key is to store the rectangle's current position as a base reference, then calculate the new coordinates directly within state property changes without any custom functions.
Full Working Example
import QtQuick 2.9 import QtQuick.Controls 2.2 ApplicationWindow { visible: true width: 640 height: 480 title: qsTr("Declarative Rectangle Movement") Rectangle { id: movableRect width: 100 height: 100 color: "steelblue" x: 50 y: 50 // Track current position as a base for next movement property real baseX: x property real baseY: y states: [ State { name: "moved" PropertyChanges { target: movableRect // Calculate new coordinates based on current base position x: baseX + 100 // Adjust X offset as needed y: baseY + 50 // Adjust Y offset as needed // Update base position to the new coordinates for next click baseX: x baseY: y } } ] transitions: [ Transition { from: "" to: "moved" // Optional smooth animation for movement SequentialAnimation { NumberAnimation { properties: "x,y"; duration: 300 } // Reset state after animation so we can trigger it again ScriptAction { script: movableRect.state = "" } } } ] } Button { text: qsTr("Move Rectangle") anchors.bottom: parent.bottom anchors.horizontalCenter: parent.horizontalCenter anchors.bottomMargin: 20 // Trigger the movement state on click onClicked: movableRect.state = "moved" } }
Breakdown of How It Works
- Base Position Tracking: The
baseXandbaseYproperties store the rectangle's current position, so each new movement calculation uses the most recent location as a starting point. - Declarative Coordinate Calculation: In the
movedstate, we directly compute the newxandyvalues using the base properties—no functions involved, just simple arithmetic binding. - Reusable Trigger: After the movement animation completes, we reset the state back to default, so clicking the button again will trigger another movement from the new position.
- Smooth Animation: The transition adds a gentle animation (you can adjust the
durationor remove it entirely if you want instant movement).
You can tweak the offset values (like +100 or +50) to any calculation you need—multiply, subtract, or use different constants—all while keeping everything strictly declarative.
内容的提问来源于stack exchange,提问作者TheWaterProgrammer
相关产品推荐
相关产品推荐

