您的位置:首页 > 移动开发

Using QML Bindings in C++ Applications(part 3)

2014-07-25 13:09 459 查看
Supported data typesAny C++ data that is used from QML -whetheras custom properties, or parameters for signals or functions - must beof a typethat is recognizable by QML.By default, QML recognizes thefollowingdata types:・ bool・ unsigned int, int・ float, double, qreal・ QStringQUrlQColorQDate, QTime, QDateTimeQPoint, QPointFQSize, QSizeFQRect, QRectFQVariantQVariantList, QVariantMapQObject*・ Enumerations declared with Q_ENUMS()To allow a custom C++ type to be createdorused in QML, the C++ class must be registered as a QML type using qmlRegisterType(),asshown in the Defining new QML elements sectionabove.JavaScript arrays andobjectsThere is built-in support for automatictypeconversion between QVariantList andJavaScript arrays,and QVariantMap andJavaScript objects.For example, the function defined inQMLbelow left expects two arguments, an array and an object, and printstheircontents using the standard JavaScript syntax for array and object itemaccess.The C++ code below right calls this function, passing a QVariantList anda QVariantMap,whichare automatically converted to JavaScript array and object values,repectively:1. //MyItem.qml2. Item {3. function readValues(anArray,anObject) {4. for (var i=0;i<anArray.length; i++)5. console.log("Array item:", anArray[i])6. 7. for (var prop in anObject) {8. console.log("Object item:", prop, "=", anObject[prop])9. }10. } 11. } 1. //C++2. QDeclarativeView view(QUrl::fromLocalFile("MyItem.qml"));3. 4. QVariantList list;5. list << 10 << Qt::green << "bottles";6. 7. QVariantMap map;8. map.insert("language", "QML");9. map.insert("released", QDate(2010, 9, 21));10. 11. QMetaObject::invokeMethod(view.rootObject(),"readValues",12. Q_ARG(QVariant,QVariant::fromValue(list)), 13. Q_ARG(QVariant,QVariant::fromValue(map)));This produces output like:1. Array item: 102. Array item: #00ff003. Array item: bottles4. Object item: language = QML5. Object item: released = TueSep 21 2010 00:00:00 GMT+1000 (EST)Similarly, if a C++ type uses a QVariantList or QVariantMap typefor a property ormethod parameter, the value can be created as a JavaScriptarray or object in theQML side, and is automatically converted to a QVariantList or QVariantMap whenit is passed to C++.Using enumerations of acustom typeTo use an enumeration from a customC++component, the enumeration must be declared with Q_ENUMS() toregisterit with Qt's meta object system. For example, the following C++ typehas a Status enum:1. class ImageViewer : public QDeclarativeItem2. {3. Q_OBJECT4. Q_ENUMS(Status)5. Q_PROPERTY(Status status READstatus NOTIFYstatusChanged)6. public:7. enum Status {8. Ready,9. Loading,10. Error11. };12. 13. Status status() const;14. signals:15. void statusChanged();16. };Providing the ImageViewer class has been registeredusing qmlRegisterType(),its Status enum can now be used fromQML:1. ImageViewer {2. onStatusChanged: {3. if (status == ImageViewer.Ready)4. console.log("Image viewer isready!")5. }6. }The C++ type must be registered with QMLtouse its enums. If your C++ type is not instantiable, it can be registeredusing qmlRegisterUncreatableType().Tobe accessible from QML, the names of enum values must begin with acapitalletter.See the Writing QML extensions with C++ tutorialand the Extending QMLFunctionalitiesusing C++reference documentation for more information.Using enumeration valuesas signalparametersC++ signals may pass enumeration valuesassignal parameters to QML, providing that the enumeration and the signalaredeclared within the same class, or that the enumeration value is one ofthosedeclared in the Qt Namespace.Additionally, if a C++ signal with anenumparameter should be connectable to a QML function using the connect()function,the enum type must be registered using qRegisterMetaType().For QML signals, enum values may be usedassignal parameters using the int type:1. ImageViewer {2. signal someOtherSignal(int statusValue)3. 4. Component.onCompleted: {5. someOtherSignal(ImageViewer.Loading)6. }7. }Automatic type conversionfrom stringsAs a convenience, some basic types canbespecified in QML using format strings to make it easier to pass simplevaluesfrom QML to C++.

(More details on these string formatsandtypes can be found in the basic type documentation.)These string formats can be used to setQML property values and passargumentsto C++ functions. This is demonstrated by various examples on thispage; in theabove Qt properties example,theApplicationData class has a backgroundColor property of a QColor type,which is set fromthe QML code with the string "red" rather ratherthan an actual QColor object.If it is preferred to pass anexplicitly-typedvalue rather than a string, the global Qt objectprovidesconveniencefunctions for creating some of the object types listed above. Forexample,Qt.rgba() createsa QColor valuefrom four RGBAvalues. The QColor returnedfrom thisfunction could be used instead of a string to set a QColor-typepropertyor to call a C++ function that requires aQColor parameter.Writing QML pluginsThe Qt Declarative module includesthe QDeclarativeExtensionPlugin class,which is anabstract class for writing QML plugins. This allows QML extensiontypes to bedynamically loaded into QML applications.See the QDeclarativeExtensionPlugin documentationand How to Create Qt Plugins formore details.Managing resource files with the QtresourcesystemThe Qt resource system allowsresource files tobe stored as binary files in an application executable. Thiscan be useful whenbuilding a mixed QML/C++ application as it enables QML files(as well as otherresources such as images and sound files) to be referred tothrough theresource system URI scheme rather than relative or absolute paths tofilesystemresources. Note, however, that if you use the resource system, theapplicationexecutable must be re-compiled whenever a QML source file is changedin orderto update the resources in the package.To use the resource system in amixedQML/C++ application:・ Create a .qrc resource collection file thatlistsresource files in XML format・ From C++, load the main QML file as aresource using the :/ prefix oras aURL with the qrcschemeOnce this is done, all files specifiedbyrelative paths in QML will be loaded from the resource system instead. Useofthe resource system is completely transparent to the QML layer; this meansallQML code should refer to resource files using relative paths andshould not use the qrc scheme. This schemeshould only beused from C++ code for referring to resource files.Here is a application packaged usingthe Qt resource system.Thedirectory structure looks like this:1. project2. |- example.qrc3. |- main.qml4. |- images5. |- background.png6. |- main.cpp7. |- project.proThe main.qml and background.png files will bepackaged asresource files. This is done in theexample.qrc resource collection file:1. <!DOCTYPE RCC>2. <RCC version="1.0">3. 4. <qresource prefix="/">5. <file>main.qml</file>6. <file>images/background.png</file>7. </qresource>8. 9. </RCC>Since background.png is a resourcefile, main.qml can refer to itusing therelative path specified in example.qrc:1. //main.qml2. import QtQuick 1.03. 4. Image { source: "images/background.png" }To allow QML to locate resource filescorrectly,the main.cpp loads the main QMLfile, main.qml, as a resource fileusingthe qrc scheme:1. int main(int argc, char *argv[])2. {3. QApplication app(argc, argv);4. 5. QDeclarativeView view;6. view.setSource(QUrl("qrc:/main.qml"));7. view.show();8. 9. return app.exec();10. }Finally project.pro uses the RESOURCESvariable to indicatethat example.qrc should be used tobuildthe application resources:1. QT += declarative2. 3. SOURCES += main.cpp4. RESOURCES += example.qrcSee The Qt Resource System formore information.Related LinksExtending QML Functionalitiesusing C++Integrating QML Code withExisting Qt UI Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: