在QML编程中,我们肯定是需要与C++进行信息交互的。本文以个人项目中使用的实例来进行讲述QML和C++信息交互。
QML和C++间的信息交互有很多方式,本文主要以信号和槽来进行交互。在本项目中,我们主要定义一个类来进行QML和C++间的信息交互,C++通过信号的方式来把信息传递给QML,QML通过槽函数来把信息传递给C++. 下面为具体的代码。
MsgInterface.h
/* c++和QML间消息交互*/
#ifndef __MSG_INTERFACE_H__
#define __MSG_INTERFACE_H__
#include<QObject>
#include<QJsonObject>
#include<mutex>
class MsgInteractive : public QObject
{
Q_OBJECT
public:
MsgInteractive ();
~MsgInteractive ();
//获取单例对象
static MsgInteractive* GetSingletonObj();
signals:
//C++ 通过信号传递信息给QML
void allSignalToQml(unsigned char index,QJsonObject msg);
public slots:
//QML通过槽函数传递信息给C++
void allInfoToC(unsigned char index,QJsonObject msg);
private:
static MsgInteractive* s_obj;
static std::mutex s_mutex;
};
#endif
#include "MsgInterface.h"
MsgInteractive* MsgInteractive ::s_obj = NULL;
s_mutex MsgInteractive ::s_mutex;
MsgInteractive ::MsgInteractive ()
{
}
MsgInteractive ::~MsgInteractive ()
{
}
//获取单例对象
MsgInteractive* MsgInteractive ::GetSingletonObj()
{
s_mutex.lock();
if(s_obj == NULL)
{
s_obj = new MsgInteractive();
}
s_mutex.unlock();
return s_obj;
}
//QML通过槽函数传递信息给C++
void MsgInteractive ::allInfoToC(unsigned char index,QJsonObject msg)
{
//对不同界面的消息进行处理
switch(index)
{
case LOGINE:
break;
case SETINFO:
break;
default:
break;
}
}
上面我们为C++定义的一个用来进行交互的接口,肯定是需要把这个类型注册到QML中才能使用,下面代码用来把C++定义的这个类注册到QML中。
QQmlApplicationEngine engine;
MsgInteractive *msgInteration = MsgInteractive::GetSingletonObj();
engine.rootContext()->setContextProperty("msgInteration",msgInteration);
下面代码为QML接受C++的消息,和把QML的消息传递给C++
Rectangle{
id:testMsg
Button{
id:testButton
text:"sendMsg"
onClicked:{
var msg= {};
msg.index = 0;
var listFileName = [];
listFileName[0]="xiaowu";
listFileName[1]="dahei";
listFileName[2]="xiaotian";
msg.fileName = listFileName;
allInfoToC.allInfoToC(2,msg);
}
}
Connections{
target:msgInteration
//打印C++传递过来的消息和内容
onMsgInteration:{
console.log("index : name: age:",index,msg.name,msg.age);
}
};
}
以上为初始测试代码,需要具体的实例代码,请订阅后私信获取。