qml与c++数据交互
1.01 c++类中使用Q_PROPERTY宏定义属性,使用绑定语法将属性与QML元素关联
#include <QObject>
class MyItem : public QObject
{
Q_OBJECT
/* 使用 Q_PROPERTY 定义交互的属性 */
Q_PROPERTY(QString name READ getName WRITE setName NOTIFY nameChangeSig)
public:
explicit MyItem(QObject *parent = nullptr) : QObject(parent), m_strItemName(""){}
/* 为属性提供 getter 和 setter 方法 */
void setName(QString name) {
if(m_strItemName != name)
{
m_strItemName = name;
emit nameChangeSig();
}
}
QString getName(){
return m_strItemName;
}
/* 将自定义 C++ 类型注册到 QML 中的函数*/
static void registerQmlType(){
qmlRegisterType<MyItem>("qmlMyItem", 1, 0, "MyItem");
}
private:
QString m_strItemName;
signals:
/* 信号与属性对应,通过信号通知其他对象属性的变化 */
void nameChangeSig();
public slots:
void slotNameChange();
};
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlEngine>
#include "myitem.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
/* 将自定义 C++ 类型注册到 QML 中的函数*/
//qmlRegisterType<MyItem>("qmlMyItem", 1, 0, "MyItem");
MyItem::registerQmlType();
QQmlApplicationEngine engine;
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
import QtQuick 2.12
import QtQuick.Window 2.12
/*引入c++类*/
import qmlMyItem 1.0
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Rectangle{
width: 50; height: 50;
color: 'red'
MouseArea {
anchors.fill: parent
onClicked: myItem.name = 'li'
}
}
MyItem {
id:myItem
/*qml值改变,触发事件*/
onNameChangeSig: {
console.log('qml Name Changed')
/*qml中通知c++对象*/
myItem.slotNameChange()
}
}
}
1.02 qml中调用c++对象方法, 使用Q_INVOKABLE宏定义函数
(1) 在c++类中通过Q_INVOKABLE声明函数:
Q_INVOKABLEvoid setByName (QString name){m_strItemName = name;}
(2) 在qml中直接使用
myItem.setByName('xiaoming')