Search code examples
qtonclickqmlqtquickcontrols2

QML-How to add another command to onClick in ui.qml?


I want to add another command to itemDelegate.onClick .

Here is my code:

ListView {
        id: beam_viewer
        x: 8
        y: 18
        width: 188
        height: 374
        delegate: ItemDelegate {
            id: delegate_item
            width: 180
            height: 25
            Text {
                text: modelData
                anchors.verticalCenter: parent.verticalCenter
            }
            onClicked: img_footprint.source = applicationPath +
                       "footprints/" + modelData + ".webp"


        }
    }

I use onClicked for change my image source and I want to use modelData for myText.text . I use ui.qml and it doesn't allow to use { } after onClicked because it reject using javascript.

How can I add to onClicked myText.text = modelData.

Thank you!


Solution

  • You probably need to move the code that uses JavaScript (e.g. the contents of the ItemDelegate that contains the Text item and whatnot) into its own .QML file that Qt Quick Designer can't see. For example:

    MainForm.ui.qml:

    ListView {
        id: beam_viewer
        x: 8
        y: 18
        width: 188
        height: 374
        delegate: MyDelegate {}
    }
    

    MyDelegate.qml:

    ItemDelegate {
        id: delegate_item
        width: 180
        height: 25
        Text {
            text: modelData
            anchors.verticalCenter: parent.verticalCenter
        }
        onClicked: img_footprint.source = applicationPath +
                   "footprints/" + modelData + ".webp"
    }
    

    Personally I just wouldn't use ui.qml files. I know that's not a very satisfying answer, but it seems to just slow me down.