首页 文章

从QML代码更改上下文属性

提问于
浏览
1

主要目标:拥有一个上下文属性,该属性由定义到QML文件(例如 file_1.qml )的项目设置,并且将在运行时由不同QML文件(例如 file_2.qml )中定义的其他项目访问 .

问题:是否可以在 file_1.qml 中设置新的上下文属性,然后在 file_2.qml 中读取此属性?

(编辑)

例如,我需要在file_1.qml中使用file_2.qml中的值:

file_1.qml:

(...)
UiController.but_generate__onClicked(
   getContextProperty("sbx_money_quantity_value"),
   cal_daysoff.visibleMonth)
(...)

file_2.qml:

(...)
SpinBox {
        id: sbx_money_quantity
        objectName: "sbx_money_quantity"
        Layout.fillWidth: true
        minimumValue: 0
        maximumValue: 100000
        value: 20000


        onChanged: setContextProperty("sbx_money_quantity_value",value)
    }
(...)

谢谢!

1 回答

  • 1

    由于范围限制,您无法从另一个文件中访问某个文件中的项目 . 所以你只需要一些代理根对象,或者可能是一些全局单例对象,或者只是将一个对象的引用传递给另一个对象 . 例如:

    File1.qml

    Item {   
        property someValue: 1
    }
    

    File2.qml

    Item {
        property variant ref: null
        onChanged: ref.someValue = 2;
    }
    

    main.qml

    File1 {
        item: file1
    }
    File2 {
        item: file2
        ref: file1
    }
    

相关问题