开发者

Calculation in a QML file?

开发者 https://www.devze.com 2023-04-12 19:10 出处:网络
I got the following code that doesn\'t work (in a QML file - PixelAdapter.qml) : Item { id: pixelAdapterId

I got the following code that doesn't work (in a QML file - PixelAdapter.qml) :

Item {
    id: pixelAdapterId

    property int in
    property int alpha
    property int out

    out = in * 10 + alpha

}

I tried :

pixelAdapterId.out = pixelAdapterId.in * 10 + pixelAdapterId.alpha

PixelAdapter.out: P开发者_如何学PythonixelAdapter.in * 10 + PixelAdapter.alpha

but everything doesn't work. I feel like I'm not doing something usual in QML but I HAVE to do some calculations with my properties, and "bind" the result of it to another property. What do I have to modify ?


You can simply bind it:

Rectangle {
   width: 100
   height: 100
   focus: true

   property int in
   property int alpha
   property int out: 10*in + alpha

   Keys.onReturnPressed: {
      console.log(out);
      in = 5; alpha =10;
      console.log(out);
      in = 6;
      console.log(out);
   }
}

You'll get meaningful results as soon as you'll bind useful values to the parameters.


One thing you have to be very careful about is accidentally resetting/breaking your property bindings.

For example if you have:

Rectangle {
   property int x
   property int y: x + 1
   property int z: 2 * y
}

Then you can execute some JavaScript somewhere that does x = 5, and then y and z will automatically update due to the binding.

However, if you do something like y = 6 in your JavaScript, then it breaks the binding, and y will no longer update when x changes.

This has caused me a great deal of grief in the past. Not sure if this helps with your question but I thought I'd throw it out there.

0

精彩评论

暂无评论...
验证码 换一张
取 消