[英]Qt QML Access a QObject by a String
我有一个 Model 暴露给 qml 上下文属性,它包含一个列表列表。 这些列表是动态创建的,然后也会暴露给 qml 上下文。
Model:
#include <QtCore>
#include <QQmlContext>
class Model : public QObject
{
Q_OBJECT
public:
Model(QQmlContext* rootContext) {
rootContext->setContextProperty(QML_NAME, this);
dataLists.push_back( new DatedValueList(rootContext, "List1", "m"));
names.push_back("List1");
}
QList<DatedValueList*> dataLists;
QString QML_NAME = "Model";
QList<QString> names;
Q_INVOKABLE QList<QString> getListNames() { return names };
};
日期值列表:
#include <QObject>
#include <QtCore>
#include <QQmlContext>
class DatedValueList: public QObject, public QList<int>
{
Q_OBJECT
public:
DatedValueList(QQmlContext* rootContext, QString i_name, QString i_unit) : name(i_name), unit(i_unit)
{
rootContext->setContextProperty(name, this);
}
QString name; //under this name it is exposed
QString unit;
Q_INVOKABLE QString getName() {return name;}
Q_INVOKABLE QString getUnit() {return unit;}
};
主要的:
#include <QtCore>
#include <QQmlContext>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
//create Controller w/ thread
QQmlContext* rootContext = engine.rootContext();
Model model(rootContext );
//load QML into engine
engine.load(QUrl(QStringLiteral("qrc:/resource/qml/MainWindow.qml")));
return app.exec();
}
在 QML 中,我现在想像这样访问这些 DatedValueLists 之一。 主窗口.qml:
import QtQuick 2.15
import QtQuick.Window 2.15
Window {
id: mainview
width: 1800
height: 768
visible: true
flags: Qt.Window
Timer {
interval: 1000 // 1 Hz
running: true
repeat: true
onTriggered: {
console.log( Model.getListNames()[0] ) // Output: List1
console.log( Model.getListNames()[0].getUnit() ) // Not working
}
}
}
第二条 output 行不工作。 它是一个字符串,我想在它上面调用一个 function。 但是我怎样才能转换它或使用字符串作为 qml 上下文 ID?
作为最低要求,您必须实现 function,它返回DatedValueList
上的Model
:
Q_INVOKABLE DatedValueList getList(const QString& name) { return ... };
但这立即带来了一个小挑战,因为您的数据结构不允许查找,因此应该迭代整个dataLists
成员。
我认为您最好从您的Model
class 提供QVariantMap
,您可以为每个列表命名并获取列表本身:
//C++
Q_PROPERTY(QVariantMap listMap ...)
//QML
model.listMap.keys()[0]
model.listMap[model.listMap.keys()[0]].getUnit()
但这甚至可能是一个糟糕的决定,具体取决于您希望如何塑造您的 UI 的 rest,我敢肯定这不会是console.log
唯一的;-)
另请注意,上下文属性的第一个字母不应大写。 您可能会在console.log
调用中实例化Model
而不是在main
中引用一个实例化
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.