Qt 在QML的选项卡视图中调用另一个QML文件中的函数或属性

Qt 在QML的选项卡视图中调用另一个QML文件中的函数或属性,qt,qml,qtquick2,tabview,Qt,Qml,Qtquick2,Tabview,我想从main.qml调用PageA.qml中的myFunc()。我尝试了一些属性别名的东西,但到目前为止没有任何效果。有什么想法吗 这是我的PageA.qml代码: import QtQuick 2.4 import QtQuick.Controls 1.2 Item { function myFunc() { /* ... */ } TextField { id: myText } } 这是我的main.qml: import QtQuick 2.4 import QtQ

我想从
main.qml
调用
PageA.qml
中的
myFunc()。我尝试了一些属性别名的东西,但到目前为止没有任何效果。有什么想法吗

这是我的
PageA.qml
代码:

import QtQuick 2.4
import QtQuick.Controls 1.2

Item {
    function myFunc() { /* ... */ }
    TextField { id: myText }
}
这是我的
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
    }
}

PageA
中调用函数的问题源于这样一个事实,即
Tab
不是从
Item
继承的,而是从
Loader
继承的,因此像
tabID.function()
这样的直接函数调用是不可能的。您需要
选项卡的
属性:

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
}
或者,您可以创建别名:

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
}

但别名与否或多或少是一个装饰性的选择。

谢谢!调用函数时忘记了.item。