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

Python 从字符串设置qml模型和属性,python,qml,pyside2,Python,Qml,Pyside2,我想通过表示此模型名称和属性的字符串在qml中设置一个模型 所以在我的最小示例中,模型是带有属性描述的otherModel。这个字符串是另一个模型myModel的一部分 在我的实际应用程序中,我从配置文件加载这些内容,其中模型名称和属性是一个字符串 class MyModel(QtCore.QObject): def __init__(self, other_model_name_and_attribute:str): QtCore.QObject.__init__(se

我想通过表示此模型名称和属性的字符串在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

然后注册模型:

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)
这里我要设置另一个模型

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

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

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

所以现在我使用了一个模型存储库,在那里我注册了所有模型,其中有一个插槽:

@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']
}

这并不像我希望的那样优雅,但现在它起作用了。

我不理解你的问题,请解释清楚。最后一个代码块是这个问题最有趣的部分。我想将“Text”views Text属性的模型设置为otherModel.description,但我只有“otherModel.description”作为字符串值。我发现你想要什么很奇怪,因为你似乎想将python功能应用于QML,在我看来,你有一个,为什么要这样做?好的,我有一个每秒钟更新一次的模型。让我们假设它是一个发动机转速和….的数据模型。在本例中,它是otherModel,然后我有一个仪表板,其中的视图显示otherModel中的值。此视图是通过解析文本配置文件并使用qml加载程序创建视图来创建的。每个视图都有一个模型,用于保存视图的宽度和高度。但它们应该显示的值在otherModel中。文本配置文件中定义了他们应该显示的otherModel的哪个值。为什么不让“other\u model\u name\u And\u attribute”直接返回otherModel而不是str?
Text {
    text: model_repo.get_model('otherModel')['rpm']
}