Qt 5.12 - QML and C ++ example mixed

1 Introduction

QML is designed to be easily expanded through C ++ code. Qt QML module class allows to load and process QML objects from C ++, Qt and QML engine and system integration of the element object properties make C ++ function can be called directly from QML. This allows developers to mix applications, the hybrid application QML, JavaScript and C ++ code realization are mixed together.

Object type 2 or exposure to Qt C ++ QML

2.1 Creating QML needs to be exposed to the type of data

#ifndef MYCLASS_H
#define MYCLASS_H
#include <QObject>
#include <QString>
class MyClass : public QObject
{
Q_OBJECT
Q_PROPERTY(QString myString READ myString WRITE setmyString NOTIFY myStringChanged)
public:
explicit MyClass(QObject *parent = 0);
Q_INVOKABLE QString getMyString();
signals:
void myStringChanged();
public slots:
void setmyString(QString aString);
QString myString();
private:
QString m_string;
};
#endif // MYCLASS_H

If you want to methods of data elements can be called directly QML There are two ways:

  • Add Q_INVOKABLE macro before the function declaration.
  • Shen Mingcheng public slots.
    QML direct access to change the attribute data elements, which is stated by the attribute QPROPERTY.

2.2 exposure Qt C ++ objects that already exist to QML

//main.cpp
MyClass myObj;
QDeclarativeEngine *engine=viewer.engine();
QDeclarativeContext *context=engine->rootContext();
context->setContextProperty("myObjectExposeByCXProperty", &myObj);
qml中可以直接使用myObjectExposeByCxProperty对象。

//mainpage.qml
...
Button{
...
id:btn1
...
text: qsTr("PROPERTY") 
//此处调用myString为MyClass的QPROPERTY的属性不是方法,所以没有括号。
onClicked: label.text=myObjectExposeByCXProperty.myString;
}

3

reference

. 1, the Qt 5.12 study notes -QML and C ++ mixed overview
2, the Overview - QML and C ++ Integration
. 3, QT development (sixty-nine) - QML and C ++ mixed programming
4, [QML and C ++ mixed programming] with QVariantList passing arrays type members
5, Qt study notes 5.12 - introduce specific macro
6, QML with C ++ objects

Published 496 original articles · won praise 601 · Views 1.55 million +

Guess you like

Origin blog.csdn.net/qq_38880380/article/details/103836138