属性 变化前后的 QML 事件

QML Event before and after property change

是否有任何我可以绑定的信号允许我在 属性 更改之前和之后直接执行功能?

例如这样的事情:

Canvas {
    id: canvas
    anchors.fill: parent

    property real lastX
    property real lastY

    property var lastContext

    function cacheImage(){
        lastContext = canvas.context
    }

    function loadImageFromCache(){
        canvas.context = lastContext
        canvas.requestPaint()
    }
}

我想在 canvas 大小改变之前调用 cacheImage() 函数,在调整大小完成后调用 loadImageFromCache() 函数。

如果我理解正确,onWidthChangedonHeightChanged 执行后者,但我需要在执行此操作之前保存图像。有没有简单的方法可以做到这一点?

这种功能不是 QML "core design intent" 的一部分,因此您无法立即使用它。

当您开始实现自己的 setter 函数时,对 C++ 对象的操作就很容易了。

但即使在 QML 中,您也可以简单地使用辅助 setter 函数,而不是直接使用 属性:

function setSomeProp(newValue) {
  if (newValue === oldValue) return
  stuffBeforeChange()
  oldValue = newValue
  stuffAfterChange() // optional, you can use the default provided signal too
}

如果你坚持使用基于属性的语法,你可以使用额外的辅助属性:

property type auxProp
onAuxPropChanged: setSomeProp(auxProp)

这将允许您使用 = 运算符以及进行绑定。

但是 cacheImage() 不必在大小更改之前立即调用!需要在最近的 canvas 内容更改之后和新的 canvas 大小生效之前随时调用它。用于缓存 canvas 的 window 非常长,并且在更改之间延伸。事件 "before n-th property change" 就是 "after (n-1)-th property change" :)