在之前,我们已经发现了父控件无法访问到子控件的属性。那么子控件是否能访问到父控件的函数呢?
子对象
//Child.qml
import QtQuick 2.0
import QtQuick.Controls 2.0
Rectangle {
id : child
property alias item_name: textItem.text
x:100
y:100
height:x
width:x
Label {
id: textItem
text: "1234"
}
Child2{
id:child2
visible:true
}
}
子对象的对象
//Child2.qml
import QtQuick 2.0
import QtQuick.Controls 2.0
Rectangle {
x:300
y:100
height:y
width:y
Component.onCompleted:
speak()
}
root对象
//main.qml
import QtQuick 2.6
import QtQuick.Window 2.2
import QtQuick.Controls 2.1
import QtQuick.Controls.Styles 1.2
import QtQuick.Dialogs 1.2
import an.qml.TransObj 1.0
//主窗体
Window {
id:window;
visible: true;
width: 600;
height: 480;
minimumWidth: 480;
minimumHeight: 380;
signal qMLSEND(string a)
property string name: "this is QML"
property bool show: false
function speak()
{
console.log("root的函数")
}
Child
{
id : rect_child
visible:show
}
TransObj{
id:transobj;
onValueFromCpp:{
console.log("value from cpp :" + val);
}
}
Button {
id: test;
text: "test";
anchors.left:parent.left;
anchors.bottom: parent.bottom;
onClicked: {
transobj.getValFromQml(123);
qMLSEND("QML");
rect.text = name
show = true
rect_child.item_name = name
}
}
Label
{
id:rect
anchors.top: window.top
anchors.left: window.left
}
}
在main.qml中,我们定义了一个函数function用来打印
然后将child对象实例在main.qml,child2实例在child中
最后打印结果
证明了无论在多少层级下,子对象永远能访问父对象的function,或者说是父对象的function全局可用。