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。