标签:style blog class code c java
如何在QML中使用我们的自定义的配置类,程序运行截图: 其中Text对象所显示的文本"fuzhou"就是从配置类中获取.
1. 自定义配置类qxSetting
class qxSetting : public QObject { Q_OBJECT public: qxSetting(QObject* parent = 0 ):QObject(parent){}; public slots: void setValue( const QString& key , const QString& value ); QString getValue( const QString& key ); private: QMap<QString,QString> mMap_; }; //========== 实现qxSetting.cpp ==================== void qxSetting::setValue(const QString &key, const QString &value) { this->mMap_.insert(key,value); } QString qxSetting::getValue(const QString &key){ return this->mMap_.value(key); }
注意: QML中只能调用类的槽函数
2. 在QML中使用
qxSetting d ; d.setValue("name","fuzhou"); QQmlApplicationEngine* engine = new QQmlApplicationEngine(); //注册 engine->rootContext()->setContextProperty("settings",&d);
完整的main.cpp
int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); qxSetting d ; d.setValue("name","fuzhou"); QQmlApplicationEngine* engine = new QQmlApplicationEngine(); engine->rootContext()->setContextProperty("settings",&d); engine->load(QUrl(QStringLiteral("qrc:///main.qml"))); // QQmlComponent cm(engine ,QUrl(QStringLiteral("qrc:///main.qml")) ); // cm.create(); return app.exec(); }
附带的qml代码(包含2个qml文件)
=> main.qml 主文件 import QtQuick 2.1 import QtQuick.Window 2.1 Window { id:mainwin visible: true width: 360 height: 360 ContactModel{ Text{ property bool isHide : false id: textid anchors.centerIn: parent text:settings.getValue("name") focus: true Keys.onSpacePressed: { if( isHide == false) hideParent() else{ parent.border.color = "lightsteelblue"; isHide = false; } } function hideParent(){ parent.border.color = "white"; isHide = true; } } } ContactModel{ Rectangle{ color: "green" anchors.centerIn: parent width : 40 height: 40 } } } //======================================== //自定义组件 ContactModel.qml import QtQuick 2.0 Rectangle{ id: boradRect width : 80 ; height: 80 border.color: "lightsteelblue" border.width: 4 radius : 8 MouseArea{ anchors.fill: boradRect drag.target: boradRect drag.axis: drag.XAndYAxis } }
---恢复内容结束---
C++跟QML的交互之配置类的应用,布布扣,bubuko.com
标签:style blog class code c java
原文地址:http://www.cnblogs.com/andy1987/p/3726085.html