前端與嵌入式開發通信之QWebChannel
最近開發中需要用到和c++開發的操作臺進行通信的的需求,就找到了這個技術,記錄一下
首先需要安裝導入 qwebchannel
npm i qwebchannel
import { QWebChannel } from "qwebchannel";
初始化qwebchannel
并封裝接收消息和發型消息的方法
initQt.js
let context;
const initQt = (callback) => {// 初始化時創建了一個QWebChannel對象,里面的第一個參數qt.webChannelTransport,只有Qt端正確地向頁面設置了webchannel才能取到,否則會是undefined。 所以要判斷qt是否存在// eslint-disable-next-line no-undefif (typeof qt != "undefined") {context = null;new QWebChannel(qt.webChannelTransport, function(channel) {// Qt channel.objects對應了Qt實現里向webchannel注冊的對象表,channel.objects.qtWebObj即為從表中取出名為"qtWebObj"的對象console.loe('調C++傳遞消息過去的方法',channel.objects)context = channel.objects.qtWebObj;context.sigUpdateStatInMap.connect(function(e) {console.log("Qt傳遞消息過來==========>", e);callback && callback(e);});});} else {console.error("初始化Qt對象失敗");}
};
/**
* 給Qt發送數據(此處封裝是為了調用不同方法發送消息)
* data數據內容
*
**/
const sendMessage = (data) => {console.error("調用Qt方法發送消息=========================>",data);if (typeof context == "undefined") {initQt();} else {if (context && data) {let messageObj = JSON.stringify(data);//我這邊c++定義的是js_MakeAudioCall方法,要改成自己的C++的方法context.js_MakeAudioCall(messageObj);}}
};//接收消息
const getMessage = (callback) => {initQt(callback);
};
使用初始化的sendMessage
和getMessage
方法
// 在onMounted方法中調用接收信息的方法并使用onMounted(() => {getMessage((e) => {console.log('Qt發送消息過來====>',e)});});//給qt發送消息 const clickBtn = () => {const data='你好QT'sendMessage(data) }