Call function or property in another QML File inside a TabView in QML

jochen picture jochen · Apr 17, 2015 · Viewed 9.3k times · Source

I want to call myFunc() in PageA.qml from the main.qml (see the onClicked event of the Button). I tried some property alias stuff, but nothing has worked so far. Any ideas?

Here is my PageA.qml code:

import QtQuick 2.4
import QtQuick.Controls 1.2

Item {
    function myFunc() { /* ... */ }
    TextField { id: myText }
}

And here is my main.qml:

import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2

ApplicationWindow {
    width: 640
    height: 480
    visible: true

    TabView {
        Tab {
            title: "Tab A"
            PageA { }
        }
        // ...
    }
    Button {
        text: "click"
        onClicked: callMyFunc()
    }

    function callMyFunc() {
        // Call myFunc() in PageA.qml or read property "text" of the TextField
    }
}

Answer

Greenflow picture Greenflow · Apr 18, 2015

Your problem to call a function in PageA stems from the fact that Tab does not inherit from Item, but from Loader hence a direct function call like tabID.function() is not possible. You need the item property of Tab:

TabView {
    Tab {
        id: tabA // Give the tab an id
        title: "Tab A"
        PageA { }
    }
    // ...
}
Button {
    text: "click"
    onClicked: callMyFunc()
}

function callMyFunc() {
    tabA.item.myFunc() // Call the function myFunc() in PageA
}

Alternatively you can create an alias:

TabView {
    id: mytabview
    property alias tabItem : tabA.item
    Tab {
        id: tabA // Give the tab an id
        title: "Tab A"
        PageA { }
    }
    // ...
}
Button {
    text: "click"
    onClicked: callMyFunc()
}

function callMyFunc() {
    mytabview.tabItem.myFunc() // Call the function myFunc() in PageA
}

But alias or not alias is more or less a cosmetic choice.