QML之全局变量
C++形式
-
根据功能定义不同类,例如:程序设置类:
class Settings : public QObject{ Q_OBJECT public: Q_PROPERTY(QString appName MEMBER m_appName) private: QString m_appName = "MyApp"; }
-
和网络类:
class Networks : public QObject{ Q_OBJECT }
-
定义一个总的类:
class GlobalObject : public QObject{ Q_OBJECT public: Q_PROPERTY(Settings* settings MEMBER m_settings) Q_PROPERTY(Networks* networks MEMBER m_networks) private: Settings* m_settings; Networks* m_networks; }
-
在main函数中创建总类的对象:
auto globalObject = new GlobalObject();
-
在QQmlEngine构建之后还未加载任何QML文件之前,将该对象设置为执行上下文对象:
engine->rootContext()->setContextObject(globalObject);