将属性传递给QML Loader创建的对象 [英] Pass properties to object created by QML Loader

查看:1021
本文介绍了将属性传递给QML Loader创建的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个加载另一个qml的QML Loader

I have a QML Loader which loads another qml

Loader { id: gaugeLoader }

PieMenu {
    id: pieMenu

    MenuItem {
        text: "Add Bar Gauge"
        onTriggered: gaugeLoader.source = "qrc:/Gauges/horizontalBarGauge.qml"
    }
    MenuItem {
        text: "Action 2"
        onTriggered: print("Action 2")
    }
    MenuItem {
        text: "Action 3"
        onTriggered: print("Action 3")
    }
}

如何传递参数来设置已加载qml的IDwidthheight等?

How can I pass parameters to set the ID, width, height and so on of the loaded qml?

推荐答案

方法1: Loader::setSource

您可以使用 Loader::setSource(url source, object properties) 函数以在构造过程中设置属性,例如:

You can use the Loader::setSource(url source, object properties) function to set the properties during construction, for example:

gaugeLoader.setSource("qrc:/Gauges/horizontalBarGauge.qml", {"width": 100, "height": 100});

请注意,您无法设置 属性,因为它不是普通的属性属性:

Note that you cannot set the id attribute in this way, because it is a not an ordinary property attribute:

创建对象实例后,其id属性的值 无法更改.虽然看起来像是普通财产,但id 属性不是普通的属性属性,并且具有特殊的语义 适用于它;例如,不可能访问myTextInput.id 在上面的示例中.

Once an object instance is created, the value of its id attribute cannot be changed. While it may look like an ordinary property, the id attribute is not an ordinary property attribute, and special semantics apply to it; for example, it is not possible to access myTextInput.id in the above example.

相反,您可以按如下方式创建属性别名:

Instead, you can create a property alias as follows:

property alias gauge: gaugeLoader.item

方法2:相对于Loader对象的几何形状

Method 2: geometry relative to Loader object

作为替代方法,可以在Loader对象上设置widthheight,并在horizontalBarGauge.qml中相对于其父对象(即Loader对象)指定宽度和高度.

As an alternative, you can set the width and height on the Loader object and specify the width and height in horizontalBarGauge.qml relative to its parent, i.e. the Loader object.

property alias gauge: gaugeLoader.item
Loader { 
    id: gaugeLoader 
    width: 100
    height: 100
}

qrc:/Gauges/horizo​​ntalBarGauge.qml:

qrc:/Gauges/horizontalBarGauge.qml:

Item {
    anchors.fill: parent
}

这篇关于将属性传递给QML Loader创建的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆