Chinaunix首页 | 论坛 | 博客
  • 博客访问: 72175
  • 博文数量: 64
  • 博客积分: 165
  • 博客等级: 入伍新兵
  • 技术积分: 370
  • 用 户 组: 普通用户
  • 注册时间: 2012-12-15 22:23
文章分类
文章存档

2013年(4)

2012年(60)

我的朋友

分类:

2012-12-31 17:05:25

内容殷实,略其皮毛然受益颇多
原文地址:

Using QML Bindings in C++ Applications

QML is designed to be easily extensible to and from C++. The classes in the Qt Declarative module allow QML components to be loaded and manipulated from C++, and through Qt's , QML and C++ objects can easily communicate through Qt signals and slots. In addition, QML plugins can be written to create reusable QML components for distribution.

You may want to mix QML and C++ for a number of reasons. For example:

  • To use functionality defined in a C++ source (for example, when using a C++ Qt-based data model, or calling functions in a third-party C++ library)
  • To access functionality in the Qt Declarative module (for example, to dynamically generate images using QDeclarativeImageProvider)
  • To write your own QML elements (whether for your applications, or for distribution to others)

To use the Qt Declarative module, you must include and link to the module appropriately, as shown on the. The  documentation shows how to build a basic C++ application that uses this module.

Core module classes

The Qt Declarative module provides a set of C++ APIs for extending your QML applications from C++ and embedding QML into C++ applications. There are several core classes in the Qt Declarative module that provide the essential capabilities for doing this. These are:

  • : A QML engine provides the environment for executing QML code. Every application requires at least one engine instance.
  • : A component encapsulates a QML document.
  • : A context allows an application to expose data to the QML components created by an engine.

A  allows the configuration of global settings that apply to all of its QML component instances: for example, the  to be used for network communications, and the file path to be used for persistent storage.

 is used to load QML documents. Each  instance represents a single document. A component can be created from the URL or file path of a QML document, or the raw QML code of the document. Component instances are instatiated through the() method, like this:

engine; component(&engine, ::fromLocalFile("MyRectangle.qml")); *rectangleInstance = component.create(); // ... delete rectangleInstance;

QML documents can also be loaded using . This class provides a convenient -based view for embedding QML components into-based applications. (For other methods of integrating QML into -based applications, see .)

Approaches to using QML with C++

There are a number of ways to extend your QML application through C++. For example, you could:

  • Load a QML component and manipulate it (or its children) from C++
  • Embed a C++ object and its properties directly into a QML component (for example, to make a particular C++ object callable from QML, or to replace a dummy list model with a real data set)
  • Define new QML elements (through -based C++ classes) and create them directly from your QML code

These methods are shown below. Naturally these approaches are not exclusive; you can mix any of these methods throughout your application as appropriate.

Loading QML Components from C++

A QML document can be loaded with  or .  loads a QML component as a C++ object; also does this, but additionally loads the QML component directly into a . It is convenient for loading a displayable QML component into a -based application.

For example, suppose there is a MyItem.qml file that looks like this:

import QtQuick 1.0 { width: 100; height: 100 }

This QML document can be loaded with  or  with the following C++ code. Using a requires calling () to create a new instance of the component, while a  automatically creates an instance of the component, which is accessible via ():

// Using QDeclarativeComponent engine; component(&engine, ::fromLocalFile("MyItem.qml")); *object = component.create(); ... delete object; // Using QDeclarativeView view; view.setSource(::fromLocalFile("MyItem.qml")); view.show(); *object = view.rootObject();

This object is the instance of the MyItem.qml component that has been created. You can now modify the item's properties using () or:

object->setProperty("width", 500); (object, "width").write(500);

Alternatively, you can cast the object to its actual type and call functions with compile-time safety. In this case the base object of MyItem.qml is an , which is defined by the  class:

*item = qobject_cast<*>(object); item->setWidth(500);

You can also connect to any signals or call functions defined in the component using () and (). See below for further details.

Locating child objects

QML components are essentially object trees with children that have siblings and their own children. Child objects of QML components can be located using the  property with (). For example, if the root item in MyItem.qml had a child  item:

import QtQuick 1.0 { width: 100; height: 100 { anchors.fill: parent objectName: "rect" } }

The child could be located like this:

*rect = object->findChild<*>("rect"); if (rect) rect->setProperty("color", "red");

If objectName is used inside a delegate of a ,  or some other element that creates multiple instances of its delegates, there will be multiple children with the same objectName. In this case, () can be used to find all children with a matching objectName.

Warning: While it is possible to use C++ to access and manipulate QML objects deep into the object tree, we recommend that you do not take this approach outside of application testing and prototyping. One strength of QML and C++ integration is the ability to implement the QML user interface separately from the C++ logic and dataset backend, and this strategy breaks if the C++ side reaches deep into the QML components to manipulate them directly. This would make it difficult to, for example, swap a QML view component for another view, if the new component was missing a requiredobjectName. It is better for the C++ implementation to know as little as possible about the QML user interface implementation and the composition of the QML object tree.

Embedding C++ Objects into QML Components

When loading a QML scene into a C++ application, it can be useful to directly embed C++ data into the QML object.  enables this by exposing data to the context of a QML component, allowing data to be injected from C++ into QML.

For example, here is a QML item that refers to a currentDateTime value that does not exist in the current scope:

// MyItem.qml import QtQuick 1.0 { text: currentDateTime }

This currentDateTime value can be set directly by the C++ application that loads the QML component, using ():

view; view.rootContext()->setContextProperty("currentDateTime", ::currentDateTime()); view.setSource(::fromLocalFile("MyItem.qml")); view.show();

Context properties can hold either  or * values. This means custom C++ objects can also be injected using this approach, and these objects can be modified and read directly in QML. Here, we modify the above example to embed a  instance instead of a  value, and the QML code invokes a method on the object instance:

class ApplicationData : public { Q_OBJECT public: Q_INVOKABLE getCurrentDateTime() const { return ::currentDateTime(); } }; int main(int argc, char *argv[]) { app(argc, argv); view; ApplicationData data; view.rootContext()->setContextProperty("applicationData", &data); view.setSource(::fromLocalFile("MyItem.qml")); view.show(); return app.exec(); } // MyItem.qml import QtQuick 1.0 { text: applicationData.getCurrentDateTime() }

(Note that date/time values returned from C++ to QML can be formatted through  and associated functions.)

If the QML item needs to receive signals from the context property, it can connect to them using the  element. For example, ifApplicationData has a signal named dataChanged(), this signal can be connected to using an onDataChanged handler within a  object:

{ text: applicationData.getCurrentDateTime() { target: applicationData onDataChanged: console.log("The application data changed!") } }

Context properties can be useful for using C++ based data models in a QML view. See the ,  and models for respective examples on using , -based models and  in QML views.

Also see the  documentation for more information.

Defining New QML Elements

While new QML elements can be , they can also be defined by C++ classes; in fact, many of the core  are implemented through C++ classes. When you create a QML object using one of these elements, you are simply creating an instance of a -based C++ class and setting its properties.

To create a visual item that fits in with the Qt Quick elements, base your class off  instead of  directly. You can then implement your own painting and functionality like any other . Note that  is set by default on because it does not paint anything; you will need to clear this if your item is supposed to paint anything (as opposed to being solely for input handling or logical grouping).

For example, here is an ImageViewer class with an image URL property:

#include #include class ImageViewer : public { Q_OBJECT Q_PROPERTY( image READ image WRITE setImage NOTIFY imageChanged) public: void setImage(const &url); image() const; signals: void imageChanged(); };

Aside from the fact that it inherits , this is an ordinary class that could exist outside of QML. However, once it is registered with the QML engine using ():

qmlRegisterType<ImageViewer>("MyLibrary", 1, 0, "ImageViewer");

Then, any QML code loaded by your C++ application or  can create and manipulate ImageViewer objects:

import MyLibrary 1.0 ImageViewer { image: "smile.png" }

It is advised that you avoid using  functionality beyond the properties documented in . This is because the backend is intended to be an implementation detail for QML, so the QtQuick items can be moved to faster backends as they become available with no change from a QML perspective. To minimize any porting requirements for custom visual items, try to stick to the documented properties in  where possible. Properties  inherits but doesn't document are classed as implementation details; they are not officially supported and may disappear between releases.

Note that custom C++ types do not have to inherit from ; this is only necessary if it is a displayable item. If the item is not displayable, it can simply inherit from .

For more information on defining new QML elements, see the  tutorial and the  reference documentation.

Exchanging Data between QML and C++

QML and C++ objects can communicate with one another through signals, slots and property modifications. For a C++ object, any data that is exposed to Qt's  - that is, properties, signals, slots and  methods - become available to QML. On the QML side, all QML object data is automatically made available to the meta-object system and can be accessed from C++.

Calling Functions

QML functions can be called from C++ and vice-versa.

All QML functions are exposed to the meta-object system and can be called using (). Here is a C++ application that uses this to call a QML function:

// MyItem.qml import QtQuick 1.0 { function myQmlFunction(msg) { console.log("Got message:", msg) return "some return value" } } // main.cpp engine; component(&engine, "MyItem.qml"); *object = component.create(); returnedValue; msg = "Hello from C++"; ::invokeMethod(object, "myQmlFunction", Q_RETURN_ARG(, returnedValue), Q_ARG(, msg)); () << "QML function returned:" << returnedValue.toString(); delete object;

Notice the () and () arguments for () must be specified as  types, as this is the generic data type used for QML functions and return values.

To call a C++ function from QML, the function must be either a Qt slot, or a function marked with the  macro, to be available to QML. In the following example, the QML code invokes methods on the myObject object, which has been set using ():

// MyItem.qml import QtQuick 1.0 { width: 100; height: 100 { anchors.fill: parent onClicked: { myObject.cppMethod("Hello from QML") myObject.cppSlot(12345) } } } class MyClass : public { Q_OBJECT public: Q_INVOKABLE void cppMethod(const &msg) { () << "Called the C++ method with" << msg; } public slots: void cppSlot(int number) { () << "Called the C++ slot with" << number; } }; int main(int argc, char *argv[]) { app(argc, argv); view; MyClass myClass; view.rootContext()->setContextProperty("myObject", &myClass); view.setSource(::fromLocalFile("MyItem.qml")); view.show(); return app.exec(); }

QML supports the calling of overloaded C++ functions. If there are multiple C++ functions with the same name but different arguments, the correct function will be called according to the number and the types of arguments that are provided.

Receiving Signals

All QML signals are automatically available to C++, and can be connected to using () like any ordinary Qt C++ signal. In return, any C++ signal can be received by a QML object using .

Here is a QML component with a signal named qmlSignal. This signal is connected to a C++ object's slot using (), so that the cppSlot()method is called whenever the qmlSignal is emitted:

// MyItem.qml import QtQuick 1.0 { id: item width: 100; height: 100 signal qmlSignal(string msg) { anchors.fill: parent onClicked: item.qmlSignal("Hello from QML") } } class MyClass : public { Q_OBJECT public slots: void cppSlot(const &msg) { () << "Called the C++ slot with message:" << msg; } }; int main(int argc, char *argv[]) { app(argc, argv); view(::fromLocalFile("MyItem.qml")); *item = view.rootObject(); MyClass myClass; ::connect(item, SIGNAL(qmlSignal()), &myClass, SLOT(cppSlot())); view.show(); return app.exec(); }

To connect to Qt C++ signals from within QML, use a signal handler with the on syntax. If the C++ object is directly creatable from within QML (see  above) then the signal handler can be defined within the object declaration. In the following example, the QML code creates a ImageViewer object, and the imageChanged and loadingError signals of the C++ object are connected to through onImagedChanged andonLoadingError signal handlers in QML:

class ImageViewer : public { Q_OBJECT Q_PROPERTY( image READ image WRITE setImage NOTIFY imageChanged) public: ... signals: void imageChanged(); void loadingError(const &errorMsg); }; ImageViewer { onImageChanged: console.log("Image changed!") onLoadingError: console.log("Image failed to load:", errorMsg) }

(Note that if a signal has been declared as the NOTIFY signal for a property, QML allows it to be received with an onChanged handler even if the signal's name does not follow the Changed naming convention. In the above example, if the "imageChanged" signal was named "imageModified" instead, the onImageChanged signal handler would still be called.)

If, however, the object with the signal is not created from within the QML code, and the QML item only has a reference to the created object - for example, if the object was set using () - then the  element can be used instead to create the signal handler:

ImageViewer viewer; view; view.rootContext()->setContextProperty("imageViewer", &viewer); view.setSource(::fromLocalFile("MyItem.qml")); view.show(); // MyItem.qml import QtQuick 1.0 { { target: imageViewer onImageChanged: console.log("Image has changed!") } }

C++ signals can use enum values as parameters provided that the enum is declared in the class that is emitting the signal, and that the enum is registered using Q_ENUMS. See Using enumerations of a custom type below for details.

Modifying Properties

Any properties declared in a QML object are automatically accessible from C++. Given a QML item like this:

// MyItem.qml import QtQuick 1.0 { property int someNumber: 100 }

The value of the someNumber property can be set and read using , or () and ():

engine; component(&engine, "MyItem.qml"); *object = component.create(); () << "Property value:" << ::read(object, "someNumber").toInt(); ::write(object, "someNumber", 5000); () << "Property value:" << object->property("someNumber").toInt(); object->setProperty("someNumber", 100);

You should always use (),  or () to change a QML property value, to ensure the QML engine is made aware of the property change. For example, say you have a custom element PushButton with a buttonText property that internally reflects the value of a m_buttonText member variable. Modifying the member variable directly like this is not a good idea:

// BAD! QDeclarativeComponent component(engine, "MyButton.qml"); PushButton *button = qobject_cast(component.create()); button->m_buttonText = "Click me";

Since the value is changed directly, this bypasses Qt's  and the QML engine is not made aware of the property change. This means property bindings to buttonText would not be updated, and any onButtonTextChanged handlers would not be called.

Any  - that is, those declared with the () macro - are accessible from QML. Here is a modified version of the  on this page; here, the ApplicationData class has a backgroundColor property. This property can be written to and read from QML:

class ApplicationData : public { Q_OBJECT Q_PROPERTY( backgroundColor READ backgroundColor WRITE setBackgroundColor NOTIFY backgroundColorChanged) public: void setBackgroundColor(const &c) { if (c != m_color) { m_color = c; emit backgroundColorChanged(); } } backgroundColor() const { return m_color; } signals: void backgroundColorChanged(); private: m_color; }; // MyItem.qml import QtQuick 1.0 { width: 100; height: 100 color: applicationData.backgroundColor { anchors.fill: parent onClicked: applicationData.backgroundColor = "red" } }

Notice the backgroundColorChanged signal is declared as the NOTIFY signal for the backgroundColor property. If a Qt property does not have an associated NOTIFY signal, the property cannot be used for  in QML, as the QML engine would not be notified when the value changes. If you are using custom types in QML, make sure their properties have NOTIFY signals so that they can be used in property bindings.

See  for further details and examples on using Qt properties with QML.

Supported data types

Any C++ data that is used from QML - whether as custom properties, or parameters for signals or functions - must be of a type that is recognizable by QML.

By default, QML recognizes the following data types:

  • bool
  • unsigned int, int
  • float, double, qreal
  • , , 
  • *
  • Enumerations declared with ()

To allow a custom C++ type to be created or used in QML, the C++ class must be registered as a QML type using (), as shown in the section above.

JavaScript Arrays and Objects

There is built-in support for automatic type conversion between  and JavaScript arrays, and  and JavaScript objects.

For example, the function defined in QML below left expects two arguments, an array and an object, and prints their contents using the standard JavaScript syntax for array and object item access. The C++ code below right calls this function, passing a  and a , which are automatically converted to JavaScript array and object values, repectively:

TypeString formatExample
// MyItem.qml { function readValues(anArray, anObject) { for (var i=0; i<anArray.length; i++) console.log("Array item:", anArray[i]) for (var prop in anObject) { console.log("Object item:", prop, "=", anObject[prop]) } } } // C++ view(::fromLocalFile("MyItem.qml")); list; list << 10 << ::green << "bottles"; map; map.insert("language", "QML"); map.insert("released", (2010, 9, 21)); ::invokeMethod(view.rootObject(), "readValues", Q_ARG(, ::fromValue(list)), Q_ARG(, ::fromValue(map)));

This produces output like:

Array item: 10 Array item: #00ff00 Array item: bottles Object item: language = QML Object item: released = Tue Sep 21 2010 00:00:00 GMT+1000 (EST)

Similarly, if a C++ type uses a  or  type for a property or method parameter, the value can be created as a JavaScript array or object in the QML side, and is automatically converted to a  or  when it is passed to C++.

Using Enumerations of a Custom Type

To use an enumeration from a custom C++ component, the enumeration must be declared with () to register it with Qt's meta object system. For example, the following C++ type has a Status enum:

class ImageViewer : public { Q_OBJECT Q_ENUMS(Status) Q_PROPERTY(Status status READ status NOTIFY statusChanged) public: enum Status { Ready, Loading, Error }; Status status() const; signals: void statusChanged(); };

Providing the ImageViewer class has been registered using (), its Status enum can now be used from QML:

ImageViewer { onStatusChanged: { if (status == ImageViewer.Ready) console.log("Image viewer is ready!") } }

The C++ type must be registered with QML to use its enums. If your C++ type is not instantiable, it can be registered using(). To be accessible from QML, the names of enum values must begin with a capital letter.

See the  tutorial and the  reference documentation for more information.

Using Enumeration Values as Signal and Method Parameters

C++ signals may pass enumeration values as signal parameters to QML, providing that the enumeration and the signal are declared within the same class, or that the enumeration value is one of those declared in the .

Likewise, invokable C++ methods parameters may be enumeration values providing that the enumeration and the method are declared within the same class, or that the enumeration value is one of those declared in the .

Additionally, if a C++ signal with an enum parameter should be connectable to a QML function using the  function, the enum type must be registered using ().

For QML signals, enum values may be used as signal parameters using the int type:

ImageViewer { signal someOtherSignal(int statusValue) Component.onCompleted: { someOtherSignal(ImageViewer.Loading) } }Automatic Type Conversion from Strings

As a convenience, some basic types can be specified in QML using format strings to make it easier to pass simple values from QML to C++.

TypeString formatExample
Color name, "#RRGGBB", "#RRGGBBAA""red", "#ff0000", "#ff000000"
"YYYY-MM-DD""2010-05-31"
"x,y""10,20"
"x,y,WidthxHeight""50,50,100x100"
"WidthxHeight""100x200"
"hh:mm:ss""14:22:55"
URL string""
"x,y,z""0,1,0"
Enumeration valueEnum value name"AlignRight"

(More details on these string formats and types can be found in the basic type documentation.)

These string formats can be used to set QML property values and pass arguments to C++ functions. This is demonstrated by various examples on this page; in the above , the ApplicationData class has a backgroundColor property of a  type, which is set from the QML code with the string "red" rather rather than an actual  object.

If it is preferred to pass an explicitly-typed value rather than a string, the global  provides convenience functions for creating some of the object types listed above. For example,  creates a  value from four RGBA values. The  returned from this function could be used instead of a string to set a -type property or to call a C++ function that requires a  parameter.

Writing QML plugins

The Qt Declarative module includes the  class, which is an abstract class for writing QML plugins. This allows QML extension types to be dynamically loaded into QML applications.

See the  documentation and  for more details.

Managing resource files with the Qt resource system

The  allows resource files to be stored as binary files in an application executable. This can be useful when building a mixed QML/C++ application as it enables QML files (as well as other resources such as images and sound files) to be referred to through the resource system URI scheme rather than relative or absolute paths to filesystem resources. Note, however, that if you use the resource system, the application executable must be re-compiled whenever a QML source file is changed in order to update the resources in the package.

To use the resource system in a mixed QML/C++ application:

  • Create a .qrc  that lists resource files in XML format
  • From C++, load the main QML file as a resource using the :/ prefix or as a URL with the qrc scheme

Once this is done, all files specified by relative paths in QML will be loaded from the resource system instead. Use of the resource system is completely transparent to the QML layer; this means all QML code should refer to resource files using relative paths and should not use the qrc scheme. This scheme should only be used from C++ code for referring to resource files.

Here is a application packaged using the . The directory structure looks like this:

project |- example.qrc |- main.qml |- images |- background.png |- main.cpp |- project.pro

The main.qml and background.png files will be packaged as resource files. This is done in the example.qrc resource collection file:

main.qml images/background.png

Since background.png is a resource file, main.qml can refer to it using the relative path specified in example.qrc:

// main.qml import QtQuick 1.0 Image { source: "images/background.png" }

To allow QML to locate resource files correctly, the main.cpp loads the main QML file, main.qml, as a resource file using the qrc scheme:

int main(int argc, char *argv[]) { app(argc, argv); view; view.setSource(("qrc:/main.qml")); view.show(); return app.exec(); }

Finally project.pro uses the RESOURCES variable to indicate that example.qrc should be used to build the application resources:

QT += declarative SOURCES += main.cpp RESOURCES += example.qrc

See  for more information.

阅读(518) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~