QML.关于子控件访问父控件函数的作用域问题

在之前,我们已经发现了父控件无法访问到子控件的属性。那么子控件是否能访问到父控件的函数呢?

子对象

//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全局可用。 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值