Experience in using QML technology in C + + programs

Source: Internet
Author: User
Tags emit

Using QML in a C + + program
The QML API is divided into three main classes--qdeclarativeengine qdeclarativecomponent and Qdecl Arativecontext. Qdeclarativeengine provides QML operating environment qdeclarativecomponent encapsulated QML Documents and Qdeclarativeco


ntext allows programs to export data to QML component instances. QML also contains a handy API for Qdeclarativeview applications by simply embedding the QML component into a new qgraphicsview. There are many details that will be discussed below. The Qdeclarativeview is mainly used in rapid prototyping applications. If you are re-improving the QT application using QML, see consolidating QML to existing QT UI code. Basic usage each application requires at least one qdeclarativeengine. Qdeclarativeengine allows the configuration of global settings to be applied to all QML component instances, such as Qnetworkaccessmanager for network communication and for permanent storage. If the application requires different settings between QML component instances, only multiple Qdeclarati veengine are required. Use the Qdeclarativecomponent class to load QML Documents. Each qdeclarativecomponent instance renders a single QML document. Qdeclarativecomponent can pass the address of a document or the original text content of a document. The URL of the document can be the address of the local file system or a network address supported by Qnetworkaccessmanager. QML component instances are created by calling the Qdeclarativecomponent::create () pattern. Load an example of a Q ML document here and create an object from it. Qdeclarativeengine *engine = new Qdeclarativeengine (parent); Qdeclarativecomponent component (Engine, Qurl::fromlocalfile ("main.qml")); Qobject *myobject = Component.create ();


The Export data QML component is instantiated with Qdeclarativecontext. The context allows the application to export data to the QML component instance. A single qdeclarativecontext can be used for all instance objects of an application or for each instance using Qdeclarativecontext to create more precise control over the export of data. If you do not pass a context to Qdeclarativecomponent::create () mode then the root context of qdeclarativeengine will be used. Data export is valid for all object instances through the root context. Simple data in order to export the data to an QML component instance application, the Context property is then accessed with Javascrip by the name of the QML property binding. The following example shows how to export a background color through Qgraphicsview to

QML file//main.cpp #include <QApplication> #include <QDeclarativeView> #include <qdeclarativecontext >

int main (int argc, char *argv[]) {qapplication app (argc, argv);

Qdeclarativeview view; Qdeclarativecontext *context = View.rootcontext (); Context->setcontextproperty ("BackgroundColor", Qcolor (Qt::yellow));

View.setsource (Qurl::fromlocalfile ("main.qml")); View.show ();

return App.exec (); }

MAIN.QML Import Qt 4.7

Rectangle {width:300 height:300

Color:backgroundcolor

Text {anchors.centerIn:parent text: "Hello Yellow world!"}} Or if you need main.cpp do not need to display the created component in Qdeclarativeview you will need to use the Q declarativeengine::rootcontext () alternative to create the Qdeclarativecontext instance. Qdeclarativeengine engine; Qdeclarativecontext *windowcontext = new Qdeclarativecontext (Engine.rootcontext ()); Windowcontext->setcontextproperty ("BackgroundColor", Qcolor (Qt::yellow));

Qdeclarativecomponent component (&engine, "main.qml"); Qobject *window = component.create (Windowcontext);

The operation of the Context property is like the standard property of the QML binding-in this case the BackgroundColor C Ontext property is changed to red then the Component object instance is automatically updated. Note Delete any Qdeclarativec

The construction of Ontext is the creator's thing. W Indowcontext must be destroyed when Windowcontext is no longer needed when the window component instance is undone. The simplest way is to make sure that it sets the window as the parent of the Windowcontext. Qdeclarativecontexts is a tree structure--each qdeclarativecontexts has a parent in addition to the root context. The child qdeclarativecontexts effectively inherits the context property of their parent. This allows the application to separate different data exports to different QML object instances with more freedom. If Qdeclarativecontext sets a context property, the same parent is also affected by the new context property that is the parent shadow. In the following example, the BA Ckground context property is the shadow of context 1 and the background context property in root context.

The structured data context property can also be used to output structured and write data to QML objects. Qobject derived types can be assigned to the context property except that Qvariant supports all existing types. The Qobject context property allows data to be structured to output and allow QML to set values. The following example creates a Custompalette object and sets it as the palette context property. Class Custompalette:public Qobject {q_object q_property (qcolor background READ background WRITE SetBackground Notif Y b ackgroundchanged) q_property (qcolor text READ text WRITE setText NOTIFY textChanged)

Public:custompalette (): M_background (Qt::white), M_text (Qt::black) {}

Qcolor background () const {return m_background;} void SetBackground (const qcolor &c) {if (c! = m_background) {M_ba Ckground = C; Emit backgroundchanged (); } }

Qcolor text () const {return m_text;} void SetText (const qcolor &c) {if (c! = m_text) {m_text = C; Emit textChanged (); } }

Signals:void textChanged ();

void Backgroundchanged ();

Private:qcolor M_background; Qcolor M_text; };

int main (int argc, char *argv[]) {qapplication app (argc, argv);

Qdeclarativeview view; View.rootcontext ()->setcontextproperty ("Palette", new Custompalette);

View.setsource (Qurl::fromlocalfile ("main.qml")); View.show ();

return App.exec (); }

QML references the Palette object and its properties in order to set the color of the background and text here is the color of the panel's text will change to blue when the window is clicked. Import Qt 4.7

Rectangle {width:240 height:320 color:palette.background

Text {anchors.centerIn:parent color:palette.text text: "Click me to Change color!"}

Mousearea {anchors.fill:parent onclicked: {palette.text = "blue";}}}

You can detect a C + + property value--in which case the Custompalette Text property must have corresponding NOTIFY information to change the property. The NOTIFY signal is a signal emitted when the property value changes. The implementation should be aware that only the value changes when the signal is emitted to prevent a dead loop. To access a bound property

No NOTIFY signal will cause QML to issue a warning message at run time. Dynamic structured data If your application is too dynamically compiling qobject types for structuring, then you can use the Qdeclarativepropertymap class constructs at run time for dynamic structured data.

Calling C + + from QML makes it possible to invoke Qobject derived types through the public slots output mode or the Q_invokable markup mode. The C + + mode can also have parameters and can return values. QML supports the following types? bool? unsigned int, int? Float, double, qreal? QString? Qurl? Qcolor? Qdate,qtime,qdatetime? Qpoint,qpointf? Qsize,qsizef? QRECT,QRECTF? Qvariant The following example shows a switch that controls the "Stopwatch" object when Mousearea is clicked. Main.cpp class Stopwatch:public Qobject {q_object public:stopwatch ();

q_invokable BOOL IsRunning () const;

Public slots:void start (); void Stop ();

Private:bool m_running; };

int main (int argc, char *argv[]) {qapplication app (argc, argv);

Qdeclarativeview view; View.rootcontext ()->setcontextproperty ("Stopwatch", new stopwatch);

View.setsource (Qurl::fromlocalfile ("main.qml")); View.show ();

return App.exec (); }

Main.qml

Import Qt 4.7

Rectangle {width:300 height:300

Mousearea {anchors.fill:parent onclicked: {if (stopwatch.isrunning ()) stopwatch.stop () Else Stopwatch.start ();}}}

It is worth noting that in this particular case there is a better way to achieve the same effect in MAIN.QML with the "Run Ning" property which will be a very good QML code//MAIN.QML Import Qt 4.7

Rectangle {

Mousearea {anchors.fill:parent onClicked:stopwatch.running =!stopwatch.running}}

Of course it can also call functions declared in QML from C + +.

Network components If the URL is passed to qdeclarativecomponent as a network resource or a QML document references a network resource qdeclarativecomponent you need to obtain network data before you can create the object. In this case qdecl arativecomponent will have Loading status. The application waits until the component calls Qdeclarativecomponent::create (). The following example shows how to load a QML file from a network resource. After the qdeclarativecomponent is created, it tests whether the component is loaded. If it is it connects the qdeclarativecomponent::statuschanged () signal otherwise call continueloading () directly. This test is necessary even if the URL can be remote only in this case the anti-component is cached. Myapplication::myapplication () {//... component = new qdeclarativecomponent (Engine, Qurl ("Http://www.example.com/mai N.qml ")); if (component->isloading ()) Qobject::connect (component, SIGNAL (statuschanged (Qdeclarativecomponent::statu s)), This, SLOT (Continueloading ())); Else

Continueloading (); }

void Myapplication::continueloading () {if (Component->iserror ()) {qwarning () << component->errors ();} else {Qobject *myobject = Component->create ();}}

The contents of the QT resource QML can be loaded from the QT resource system using the Qrcurl scheme. For example [PROJECT/EXAMPLE.QRC] <! DOCTYPE rcc> &LT;RCC version= "1.0″>

<qresource prefix= "/" > <file>main.qml</file> <file>images/background.png</file> < /qresource>

</RCC>

[Project/project.pro] QT + = Declarative

SOURCES + = main.cpp RESOURCES + = EXAMPLE.QRC

[Project/main.cpp] int main (int argc, char *argv[]) {qapplication app (argc, argv);

Qdeclarativeview view; View.setsource (Qurl ("qrc:/main.qml")); View.show ();

return App.exec (); } [PROJECT/MAIN.QML] import Qt 4.7

Image {Source: "Images/background.png"}

Please note that the resource system is not accessible directly from QML. If the primary QML file is loaded as a resource all files are specified in QML as relative paths are loaded from the resource system. The use of resource systems at the QML level is completely transparent. This also means that if the primary QML file is not loaded as a resource then the resource system cannot be accessed from QML.
1. Here are the main examples of how to call the functions in QML in C + + and set the properties in QML 2. Specific code

UICTEST.QML Import Qt 4.7 Rectangle {id:mainwidget; width:640 height:480 function Callbyc (v) {Mainwidget.color = V ; return "Finish"; } rectangle{id:secondrect; x:100; y:20; width:400; height:300; rectangle{x:10; y:20; width:30; height:40; color: "#FF035721" Text {objectName: "needfindobj"; anchors.fill:parent;

Text: "";}}}

Main.cpp #include <QtGui/QApplication> #include <QtDeclarative/QDeclarativeView> #include < qtdeclarative/qdeclarativeengine> #include <QtDeclarative/QDeclarativeComponent> #include < qtdeclarative/qdeclarativecontext> #include <QtDeclarative/QDeclarativeItem> #include <QMetaObject> int main (int argc, char *argv[]) {qapplication A (argc, argv); Qdeclarativeview Qmlview; Qmlview.setsource (Qurl::fromlocalfile (". /uictest/uictest.qml ")); Qmlview.show (); Gets the root node is the node in QML where ID is mainwidget qdeclarativeitem *item = qobject_cast<qdeclarativeitem*> (Qmlview.rootobject ()) ; Item->setproperty ("Color", Qvariant ("Blue")); Find the node root we need is objectname needfindobj to get and set his Text property Qdeclarativeitem *item1 = Item->findchild<qdeclarativeitem *& gt; ("Needfindobj"); if (item1) {item1->setproperty ("text", Qvariant ("OK")),}//Call the function in QML, respectively, where the function is the object function name return value parameter Qvariant Returnvar; Qvariant arg1 = "Blue"; Qmetaobject::invokemethod (item, "CALLBYC", q_reTurn_arg (Qvariant, Returnvar), Q_arg (Qvariant, arg1)); Qdebug ("%s", Returnvar.tostring (). Tolocal8bit (). data ()); return A.exec (); }

Description

The root node here is a rectangular element with ID Mainwidget then you can set his properties directly after getting the root node in C + +. Other properties can also be called by calling functions within the specified node through InvokeMethod in Qmetaobject. Finally all about the QML and C + + interaction section is basically finished if you want more things or some other way to strongly see if http://doc.qt.nokia.com/4.7-snapshot/qtbinding.html or help documents are not in my document No, it's not.


Experience in using QML technology in C + + programs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.