QT Mobile Application Development (VI): QML interaction with C + +

Source: Internet
Author: User

QT Mobile Application Development (VI): QML interaction with C + +

The previous article described a possible way to achieve scene switching in Qt Quick, where scene switching is a technical difficulty that must be faced in applications such as games, so there is no way to switch scenes and design according to their own habits.

This article mainly introduces how to use QML and C + + to interact, the difficulty is slightly larger, suitable for experienced QT developers to learn and exchange.

QT 5 absorbs the benefits of the QT 4 declarative module, making changes to the bottom layer, creating QPA layers, isolating different operating system APIs and upper QT code, while Qml/qtquick can run smoothly on different platforms. In addition, given that the QT program is allowed to access different library functions, QT opens the interface to let the QML layer and C + + code interact. There have been more articles about QML and C + + interaction, this article only as a useful supplement, more relevant knowledge can query QT Help document or message to me.

The examples in this article were successfully compiled and run through QT 5.3.1.

original article, against undeclared references. Original Blog address:http://blog.csdn.net/gamesdev/article/details/37359873

First, a simpler approach is to register the context property, allowing QML to access C + + variables. The code is as follows:

#include <QApplication> #include <QQmlApplicationEngine> #include <qqmlcontext>int main (int argc, Char *argv[]) {    qapplication app (argc, argv);    Qqmlapplicationengine engine;    Engine.rootcontext ()->setcontextproperty (                "greeting",                qobject::tr ("Hello QML from C + +"));    Engine.load (Qurl (qstringliteral ("qrc:///main.qml"));    return app.exec ();}

Then simply call the "greeting" variable name in QML to access it smoothly.

Import QtQuick 2.2import qtquick.controls 1.1applicationwindow{    visible:true    width:640    height:480    TITLE:QSTR ("Test qml for C + + interaction")    menubar:menubar    {        menu        {            title:qstr ("file")            MenuItem            {                text:qstr ("Exit")                OnTriggered:Qt.quit ();    }}} The Text    {        Text:qstr ("This example is used to test QML and C + + interactions")        anchors.right:parent.right        Anchors.bottom: Parent.bottom    }    Text    {        text:greeting        anchors.centerIn:parent    }}

The demo program is as follows:

An important part of this example is the Qqmlcontext instance pointer. It is obtained by Qqmlapplicationengine::rootcontext () or by Qqmlapplicationengine:: Contextforobject (Constqobject * object) To obtain. When Qqmlobject is created, a qqmlcontext is instantiated to support the context properties provided for the running environment.

Using context properties allows QML to access C + + data, so how do you use QML to access C + + functions? Here we register the QML class or Singleton in C + + to get qml to gain access to C + + functions. Let's start by introducing how to register C + + classes in QML into QML. First you need to define a C + + class that inherits from Qobject and then writes:

#ifndef cplusplusclass_h#define cplusplusclass_h#include <qobject>class cplusplusclass:public QObject{    Q_ OBJECT    q_property (int rating READ rating) public:    Explicit Cplusplusclass (qobject* pparent = q_nullptr):        Q Object (pparent)    {        m_rating = 5;    }    q_invokable void Method (void)    {        qdebug ("[c++]%s is called.", __function__);    }    int rating (void) {return m_rating;} Private:    int m_rating;}; #endif//Cplusplusclass_h

Then the main.cpp need to call the Qmlregistertype () template function to register the C + + class into QML, a typical usage is as follows:

#include <QApplication> #include <QQmlApplicationEngine> #include <QtQml> #include " CPlusPlusClass.h "int main (int argc, char *argv[]) {    qapplication app (argc, argv);    First Register class    qmlregistertype<cplusplusclass> (                "cplusplus.test",/           /Uniform Resource Identifier                1,//                          major version                0,                          ///Minor version                "Cplusplustype");          QML class name    qqmlapplicationengine engine;    Engine.load (Qurl (qstringliteral ("qrc:///main.qml"));    return app.exec ();}

Finally, the properties and methods of C + + classes can be successfully accessed in QML:

Import QtQuick 2.2import qtquick.controls 1.1import cplusplus.test 1.0applicationwindow{    visible:true    width: 640    height:480    title:qstr ("Test qml for C + + interaction")    menubar:menubar    {        menu        {            title:qstr ("File" )            MenuItem            {                text:qstr ("Exit")                OnTriggered:Qt.quit ();    }}} The Text    {        Text:qstr ("This example is used to test QML and C + + interactions")        anchors.right:parent.right        Anchors.bottom: Parent.bottom    }    cplusplustype    {        id:thetype    }    mousearea    {        Anchors.fill: Parent        onclicked:        {            console.log ("[QML] Rating is:" + thetype.rating);            Thetype.method ();}}}    

Click on the form and the results of the console run are as follows:

QML: [QML] Ratingis:5

[C++]method iscalled.

If you do not want to create multiple qobject in the QML and C + + environment, or if you want to more easily access C + + methods, then consider registering a singleton class, registering the Singleton class and registering the common class is similar, but there are some notable differences, first of all to establish such a class inherited from Qobject, The code is as follows:

#ifndef cplusplusclass_h#define cplusplusclass_h#include <qobject>class cplusplusclass:public QObject{    Q_ OBJECT    q_property (int rating READ rating) public:    Explicit Cplusplusclass (qobject* pparent = q_nullptr):        Q Object (pparent)    {        m_rating = 5;    }    q_invokable void Method (void)    {        qdebug ("[c++]%s is called.", __function__);    }    int rating (void) {return m_rating;} Private:    int m_rating;}; #endif//Cplusplusclass_h

And then the key in Main.cpp, in addition to calling the Qmlregistersingletontype () template function, you also need to write a static global registration function. The code is as follows:

#include <QApplication> #include <QQmlApplicationEngine> #include <QtQml> #include " CPlusPlusSingleton.h "//Register a singleton function static qobject* Cplusplussingletonregisterfunc (qqmlengine* pqmlengine, Qjseng    ine* pjsengine) {q_unused (pqmlengine);    Q_unused (Pjsengine);    cplusplussingleton* Psingleton = new Cplusplussingleton; return Psingleton;}    int main (int argc, char *argv[]) {qapplication app (argc, argv); First register the Singleton qmlregistersingletontype<cplusplussingleton> ("Cplusplus.test",//                 A resource identifier 1,//major version 0,//minor version   "Cplusplussingleton",//single case name Cplusplussingletonregisterfunc);    function name Qqmlapplicationengine engine;    Engine.load (Qurl (qstringliteral ("qrc:///main.qml")); return app.exec ();}

In this way, the C + + part is done. The next step in QML is simple:

Import QtQuick 2.2import qtquick.controls 1.1import cplusplus.test 1.0applicationwindow{    visible:true    width: 640    height:480    title:qstr ("Test qml for C + + interaction")    menubar:menubar    {        menu        {            title:qstr ("File" )            MenuItem            {                text:qstr ("Exit")                OnTriggered:Qt.quit ();    }}} The Text    {        Text:qstr ("This example is used to test QML and C + + interactions")        anchors.right:parent.right        Anchors.bottom: Parent.bottom    }    mousearea    {        anchors.fill:parent        onclicked:        {            console.log ("[ QML] Rating is: "+ cplusplussingleton.rating);            Cplusplussingleton.method ();}}}    

Click on the form and the console results are as follows:

QML: [QML] Ratingis:5

[C++]method iscalled.

You can choose whether you want to register the QML class in C + + and register C + + singleton to get the corresponding characteristics.

In my first independent game "take Medicine", in order to successfully access the Advertising SDK, you need to write C + + code to ensure that QML can access the functions of C + +, the ads display the effect is as follows:

This article participated in the CSDN Bowen contest , please support me, vote for me!

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.