在 QML 中重新设置视觉项的更好方法

dte*_*ech 5 qt reparenting qml qt-quick qtquick2

似乎在 QML 的设计中用户 reparent 并没有真正“设想”,因为即使有可能,它也涉及创建和更改状态,这只是不方便添加到每个项目。

 import QtQuick 1.0

 Item {
     width: 200; height: 100

     Rectangle {
         id: redRect
         width: 100; height: 100
         color: "red"
     }

     Rectangle {
         id: blueRect
         x: redRect.width
         width: 50; height: 50
         color: "blue"

         states: State {
             name: "reparented"
             ParentChange { target: blueRect; parent: redRect; x: 10; y: 10 }
         }

         MouseArea { anchors.fill: parent; onClicked: blueRect.state = "reparented" }
     }
 }
Run Code Online (Sandbox Code Playgroud)

我想知道是否有一种更优雅的方式来重新设置项目而不用不必要的状态污染项目?

小智 5

不确定是否需要使用 QtQuick 1.0,但使用 2.0 这也可以,而且更直接。

导入 QtQuick 2.0

物品 { 宽度:200;高度:100

Rectangle { id: redRect width: 100; height: 100 color: "red" } Rectangle { id: blueRect x: redRect.width width: 50; height: 50 color: "blue" MouseArea { anchors.fill: parent; onClicked: { blueRect.parent = redRect; blueRect.x = 10; blueRect.y = 10 } } } }
Run Code Online (Sandbox Code Playgroud)