[Interest] QML property vs. id.property

Sze Howe Koh szehowe.koh at gmail.com
Sun Oct 6 14:52:41 CEST 2024


Hello Alexander,


On Sun, 6 Oct 2024 at 04:35, Alexander Dyagilev <alervdvcw at gmail.com> wrote:
>
> Hello,
>
> I'm getting different results if I use object's id or not when accessing its property.
>
> Let's look at this code example:
>
> Window {
>     id: root
>
>     property var x
>
>     Text {
>         visible: x
>         text: "test"
>     }
> }
>
> Text is invisible, as it should be.

It's invisible for a different reason. Text (Item) already has an "x"
property: https://doc.qt.io/qt-6/qml-qtquick-item.html#x-prop

`visible: x` refers to the Text's x-position, which is 0 here.


> But if I replace "visible: x" with "visible: root.x" when Text becomes visible and I'm getting the following error in the Application's output pane: "Unable to assign [undefined] to bool".
>
> If I change "property var x" to "property var x: null" then I'm able to access it using root.x with no issues.
>
> What is happening here? Is this a bug or an expected behavior?

Writing `property var x` is equivalent to writing `property var x:
undefined` since you didn't give it an initial/default value. Is it
expected that [undefined] does not implicitly convert to bool? I don't
have an official answer, but I certainly won't want my code to rely on
undefined variables.

Here are some other suggestions (unless you have a good reason):
* Avoid the `var` type. Specify the exact type instead (like `bool`,
`int`, `list<int>`, `QtObject` etc.)
* Avoid shadowing existing properties (Window also already has an "x"
property: https://doc.qt.io/qt-6/qml-qtquick-window.html#x-prop )


Regards,
Sze-Howe


More information about the Interest mailing list