从字符串设置qml模型和属性

问题描述 投票:0回答:1

我想从表示此模型名称和属性的字符串中以qml设置模型。

因此,在我的最小示例中,模型是具有属性描述的otherModel。并且此字符串是另一个模型myModel的一部分。

在我的真实应用程序中,我从配置文件中加载了这些东西,其中模型名称和属性是一个字符串。

class MyModel(QtCore.QObject):
    def __init__(self, other_model_name_and_attribute:str):
        QtCore.QObject.__init__(self)
        self._other_model_name_and_attribute = other_model_name_and_attribute

    @QtCore.Property(str, constant=True)
    def other_model_name_and_attribute(self) -> str:
        return self._other_model_name_and_attribute

class OtherModel(QtCore.QObject):
    def __init__(self, description:str):
        QtCore.QObject.__init__(self)
        self._description = description

    @QtCore.Property(str, constant=True)
    def description(self) -> str:
        return self._description

然后注册模型:

mm = MyModel(other_model_name_and_attribute='otherModel.description')
om = OtherModel(description='Hello')
self._view.context.setContextProperty('myModel', mm)
self._view.context.setContextProperty('otherModel', om)

并且在这里我要设置otherModel

Repeater {
  model: myModel
  delegate: Item {
    Text {
        text: myModel.other_model_name_and_attribute  # or 'otherModel.description'
    }
  }
}

最后一个代码块对此问题最有趣。我想将“文本”视图文本属性的模型设置为otherModel.description,但是我只有'otherModel.description'作为字符串值。

那么如何从字符串设置qml模型和属性?

python qml pyside2
1个回答
0
投票

所以现在我去了一个[[模型库,在那里我注册了所有带有插槽的模型:

@QtCore.Slot(str, result='QVariant') def get_model(self, model_name): return self._models[model_name]
然后在qml中我可以做:

Text { text: model_repo.get_model('otherModel')['rpm'] }

这不像我希望的那样优雅,但是现在可以了。
© www.soinside.com 2019 - 2024. All rights reserved.