[Interest] Qml/qmlllint: coercion / typecasts possible?

Nils Jeisecke nils.jeisecke at saltation.com
Mon Aug 21 16:49:38 CEST 2023


Hi list,

import QtQuick
import QtQuick.Window
import QtQuick.Layouts

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    component Foo : Text {
        required property int index
        text: "Item " + index
    }

    ColumnLayout {
        id: layout
        Repeater {
            model: 10
            delegate: Foo {}
        }
    }

    MouseArea {
        anchors.fill: layout
        onClicked: function(mouse) {
            const item = layout.childAt(mouse.x, mouse.y);
            if (item) {
                const index = item.index;
                console.log("clicked", item, "index", index)
            }
        }
    }
}

This will create ten instances of Foo. On clicking an item this prints
something like "qml: clicked Foo(0x600000a07e20) index 6"  to the
console.

So far so good.

Now qmllint rightfully complains:

Warning: Main.qml:29:36: Member "index" not found on type "QQuickItem"
[missing-property]

I'd like to coerce item to be "Foo", but it seems there is no such
thing like type casting in Qml's javascript world:

const item = layout.childAt(mouse.x, mouse.y) as Foo; // doesn't work
(item is null then).
const item : Foo = layout.childAt(mouse.x, mouse.y); // Type
annotations are not permitted in variable declarations

The only solution I've found so far is using an interim Qml property:

    MouseArea {
        property Foo clickedItem

        anchors.fill: layout
        onClicked: function(mouse) {
            clickedItem = layout.childAt(mouse.x, mouse.y);
            if (clickedItem) {
                const index = clickedItem.index;
                console.log("clicked", clickedItem, "index", index)
            }
        }
    }

This makes qmllint happy. It doesn't even complain about "clickedItem
= true" (only runtime error "Error: Cannot assign bool to
Main_QMLTYPE_1_1*").

Any better ideas?

Nils


More information about the Interest mailing list