【问题标题】:Call function or property in another QML File inside a TabView in QML在 QML 中的 TabView 内调用另一个 QML 文件中的函数或属性
【发布时间】:2015-06-24 21:48:06
【问题描述】:

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

这是我的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
    }
}

【问题讨论】:

    标签: qt qml qtquick2 tabview


    【解决方案1】:

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

    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。
    猜你喜欢
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 2018-12-06
    • 1970-01-01
    相关资源
    最近更新 更多