在 QML 中的 TabView 内调用另一个 QML 文件中的函数或属性

joc*_*hen 5 qt qml tabview qtquick2

我想从myFunc()打来电话(请参阅的事件)。我尝试了一些属性别名的东西,但到目前为止没有任何效果。有任何想法吗?PageA.qmlmain.qmlonClickedButton

这是我的PageA.qml代码:

import QtQuick 2.4
import QtQuick.Controls 1.2

Item {
    function myFunc() { /* ... */ }
    TextField { id: myText }
}
Run Code Online (Sandbox Code Playgroud)

这是我的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
    }
}
Run Code Online (Sandbox Code Playgroud)

Gre*_*low 4

您调用函数的问题PageA源于以下事实:Tab不继承自Item,但因此不可能进行Loader直接函数调用。tabID.function()您需要item以下属性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
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以创建一个别名:

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
}
Run Code Online (Sandbox Code Playgroud)

但别名或不别名或多或少是一种装饰性的选择。