Search code examples
qmlqt6qmllint

How can you downcast in QML JavaScript?


Javascript is a dynamically typed language and to the best of my knowledge has no concept of static type checking...

But QML's qmllint program tries to apply static type checking to the Javascript subset of a QML document and gives a warning for this code:

[build] Warning: /home/user/project/Plot.qml:162:2: Member "colorAccess" not found on type "QQuickItem" [missing-property]

[build] itemAt(index).colorAccess.value = "" + newColor
[build]               ^^^^^^^^^^^

The surrounding element is a Repeater. QMLLint looks into the qmltypes file and sees that it has a function itemAt that returns a QQuickItem*. But the complete story is, that we only use delegates that do have a colorAccess property. How can we teach the linter this knowledge?


Solution

  • For this case, as-Type-assertions should be used according to the QML documentation. This is unfortunately not explained in the documentation of QMLLint, but only on the linked page, as far as I can see https://doc.qt.io/qt-6/qtqml-javascript-hostenvironment.html#type-annotations-and-assertions

    Therefore:

    (itemAt(index) as TypeOfTheDelegate).colorAccess = ...
    

    I think this does not pay off for us, and we will have to keep the warnings of QMLLinter in our codebase.