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

标签 qt qml qtquick2 tabview

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

这是我的 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() 这样的直接函数调用是不可能的。您需要 itemTab 属性:

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
}

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

关于qt - 在 QML 中的 TabView 内调用另一个 QML 文件中的函数或属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29709427/

相关文章:

c++ - 用于定期调用函数的 QTimer 的非空闲替代方案

c++ - Lambda 捕获 QFile 对象

html - 带有 <hr> 行的 QML 文本

javascript - 类型转换 : Component to RadioButtonStyle

qt - 缩放 QtQuick 绘制的项目

c++ - 控制台上的 Qt 应用程序文本流

c++ - QWidget和Qml在触摸屏的处理上有什么不同?

android - Qt/QML SwipeDelegate 在移动设备(Android、iOS)上无法正常工作

java - 未调用静态对象的 Android ctor

c++ - Qt 4.8 用于旋转qgraphicsitem的Qtransform