QtQuick一分钟技巧:使用C++保存全局数据

#ifndef QMLGLOBALDATA_H
#define QMLGLOBALDATA_H

#include 
#include
#include
using namespace  std;
class QmlGlobalData : public QObject
{
    Q_OBJECT
public:

    explicit QmlGlobalData(QObject *parent = 0);
    Q_INVOKABLE  void _set(QString name,QVariant  d)
    {
        datas[name] = d;
    }

    Q_INVOKABLE  QVariant _get(QString name)
    {
        if(datas[name]!=NULL)
        {
            return datas[name];
        }
        //如果不存在字段 返回 undefined
        return QVariant("");
    }

signals:

public slots:
private:
    std::map  datas;
};

#endif // QMLGLOBALDATA_H
    Component.onCompleted: {
            Global._set("width",100)
             Global._set("height",80)
             Global._set("title","Hello")
            console.log(Global._get("width"))
            console.log(Global._get("height"))
            console.log(Global._get("title"))
            console.log(Global._get("xxx"))//尝试获取一个不存在的数据
        }
打印
qml: 100
qml: 80
qml: Hello
qml: undefined

你可能感兴趣的:(Qt,Quick)