Qt Mobile Application Development (6): Interaction Between QML and C ++

Source: Internet
Author: User

Qt Mobile Application Development (6): Interaction Between QML and C ++

Qt Mobile Application Development (6): Interaction Between QML and C ++

 

In the previous article, we talked about a possible way to implement scenario switching in Qt Quick. Scenario switching is a technical difficulty that must be faced by applications such as games, therefore, there is no way to switch the scenario. You can design it based on your usage habits.

This article mainly introduces how to use QML to interact with C ++, which is relatively difficult and suitable for experienced Qt developers to learn and communicate.

Qt 5 absorbs the advantages of the declarative module of Qt 4, makes changes to the underlying layer, creates a QPA layer, and isolates APIs of different operating systems and upper-layer Qt code, at the same time, QML/QtQuick can run smoothly on different platforms. In addition, given that the Qt program is connected to different library functions, Qt opens an interface to allow the QML layer to interact with C ++ code. I have already published many articles about QML interaction with C ++. This article is only a useful supplement. For more information, see the Qt help document or leave a message to me.

The example in this article is successfully compiled and run in Qt 5.3.1.

Original article, opposed to unstated reference. Original blog address: http://blog.csdn.net/gamesdev/article/details/37359873

The first simple method is to register the Context Property so that QML can access the C ++ variable. 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, you can access QML by simply calling the "Greeting" variable name.

 
Import QtQuick 2.2 import QtQuick. controls 1.1 ApplicationWindow {visible: true width: 640 height: 480 title: qsTr ("test qml interaction in c ++") menuBar: MenuBar {Menu {title: qsTr ("file") MenuItem {text: qsTr ("exit") onTriggered: Qt. quit () ;}}text {Text: qsTr ("this example is used to test the interaction between QML and C ++") 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 through QQmlApplicationEngine: rootContext (), or through QQmlApplicationEngine: contextForObject (constQObject * object. When a QQmlObject is created, a QQmlContext is instantiated to support context Attributes provided for the runtime environment.

The context attribute allows QML to access C ++ data. How can we use QML to access C ++ functions? Here we register the QML class or Singleton in C ++ to allow QML to access the C ++ function. First, we will introduce how to register the C ++ class in QML to QML. First, define a C ++ class that inherits from QObject, and then write it 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 ):        QObject( 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, in main. cpp, you need to call the qmlRegisterType () template function to register the C ++ class to 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 the qmlRegisterType class <CPlusPlusClass> (" CPlusPlus. test ", // Uniform Resource Identifier 1, // master version 0, // Times version" CPlusPlusType "); // QML class name QQmlApplicationEngine; engine. load (QUrl (QStringLiteral ("qrc: // main. qml "); return app.exe c ();}
 

Finally, you can smoothly access the attributes and methods of the C ++ class in QML:

 
Import QtQuick 2.2 import QtQuick. controls 1.1 import CPlusPlus. test 1.0 ApplicationWindow {visible: true width: 640 height: 480 title: qsTr ("Test qml interaction in c ++") menuBar: MenuBar {Menu {title: qsTr ("file") MenuItem {text: qsTr ("exit") onTriggered: Qt. quit () ;}}text {Text: qsTr ("this example is used to test the interaction between QML and C ++") 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 the form. The console running result is as follows:

Qml: [qml] Ratingis: 5

[C ++] method iscalled.

If you do not want to create multiple qobjects in the qml and C ++ environments or want to more easily access the C ++ method, you can consider registering a singleton class, registering a singleton class is similar to registering a common class, but there are also some significant differences. First, create a class that inherits 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 ):        QObject( 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
 

In main. cpp, besides 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 the singleton function static QObject * Handler (QQmlEngine * pQMLEngine, QJSEngine * pJSEngine) {Q_UNUSED (pQMLEngine); Q_UNUSED (pJSEngine); *** pSingleton = new handler; return pSingleton;} int main (int argc, char * argv []) {QApplication app (argc, argv); // register the singleton qmlRegisterSingletonType <CPlusPlusSingleton> ("CPlusPlus. test ", // Uniform Resource Identifier 1, // master version 0, // Times version" CPlusPlusSingleton ", // Singleton name CPlusPlusSingletonRegisterFunc); // function name QQmlApplicationEngine; engine. load (QUrl (QStringLiteral ("qrc: // main. qml "); return app.exe c ();}
 

In this way, the C ++ part is complete. In QML, the following is simple:

 
Import QtQuick 2.2 import QtQuick. controls 1.1 import CPlusPlus. test 1.0 ApplicationWindow {visible: true width: 640 height: 480 title: qsTr ("Test qml interaction in c ++") menuBar: MenuBar {Menu {title: qsTr ("file") MenuItem {text: qsTr ("exit") onTriggered: Qt. quit () ;}}text {Text: qsTr ("this example is used to test the interaction between QML and C ++") anchors. right: parent. right anchors. bottom: parent. bottom} MouseArea {anchors. fill: parent onClicked: {console. log ("[qml] Rating is:" + CPlusPlusSingleton. rating); CPlusPlusSingleton. method ();}}}
 

Click form. The console result is as follows:

Qml: [qml] Ratingis: 5

[C ++] method iscalled.

You can choose whether to register the QML class in C ++ and register the C ++ Singleton as needed to obtain the corresponding features.

In my first independent game "taking medicine", to smoothly access the ad SDK, I need to write C ++ Code to ensure that QML can access C ++ functions, the ad display effect is as follows:

This article participated in the CSDN blog contest. Please support me and vote for me!

Related Article

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.