qt - 如何将属性传递给Loader创建的对象?

标签 qt qml loader

我有一个QML Loader可以加载另一个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等?

最佳答案

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

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

请注意,您不能以这种方式设置 id attribute,因为它不是普通的属性属性:

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.



相反,您可以按如下方式创建属性别名:
property alias gauge: gaugeLoader.item

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

或者,您可以在width对象上设置heightLoader,并指定horizontalBarGauge.qml相对于其父对象(即Loader对象)的宽度和高度。
property alias gauge: gaugeLoader.item
Loader { 
    id: gaugeLoader 
    width: 100
    height: 100
}

qrc:/Gauges/horizo​​ntalBarGauge.qml:
Item {
    anchors.fill: parent
}

关于qt - 如何将属性传递给Loader创建的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44271158/

相关文章:

c - ELF 文件中的程序头和节头

file - 用于 opengl 的 3DS 文件加载器

c++ - Qt示例无法在Ubuntu上运行

c++ - Qt 测试 QVERIFY2() string 和 int 连接

xcode - XCode和Qt之间的犹豫

c++ - 在 QML 场景中显示内存中的网格

qt - 拉伸(stretch)元素以包含所有子元素

网页包 "cannot find module"

qt - 使用 QImage 加载和保存图像是否无损?

javascript - 你如何使用 JavaScript 在 QtQuick Qml 中进行大量数学运算