Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

otherway aroun: how to call qml function from javascript file?



  • Hello guys,

    im looking for a way to call QML function from inside of JS file, so lets say I have this:

    main.qml:

    ApplicationWindow {
        id: mainWindow
        width: 480
        height: 800
        title: qsTr("testapp")
    
        StackView {
            id: view
            anchors.fill: parent
            initialItem: view_ChoiseOffline
        }
        Component {
            id: view_ChoiseOffline
            ChoiseOffline {}
        }
    }
    

    ChoiseOffline.qml:

    import 'JavaScript.js' as JS
    Item {
            id: parentObject
    	Component.onCompleted: { JS.testFromJS(); }
    	
    	MouseArea {
    		id: mouseAreaID
    		anchors.fill: parent
    		function testFunction() { console.log("test passed"); }
    		onClicked: { testFunction(); }
    	}
    }
    

    JavaScript.js

    function testFromJS() {
        console.log("script inside JS works fine");    // this works fine
        testFunction();                                // this gives me error
    }
    

    obviously caling testFunction() and JS.testFromJS() from QML works fine...
    however when I call the testFunction() from JS file gives the error:

    ReferenceError: testFunction is not defined
    

    i tried several options of calling it, like parentObject.testFunction() or even view.currentItem.testFunction() and view.currentItem.parentObject.testFunction() or view.currentItem.mouseAreaID.testFunction() but nothing works...

    Can I ask for advice how to call QML function form JS file?
    I just need to keep the function inside the ChoiseOffline.qml file, so moving it out to main.qml is not an option to me.

    Any help appriciated



  • Its not in the same scope. How would it even know it exists?
    Either pass the function or the object to the JS function:

    Component.onCompleted: { JS.testFromJS(mouseAreaID); }
    ...
    function testFromJS(obj) {
      obj.testFunction()
    }
    

Log in to reply