C++ 与QML消息交互

        在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);
        }
    };
}

以上为初始测试代码,需要具体的实例代码,请订阅后私信获取。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dreamliweiming

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值