qt和vue交互

1、首先在vue项目中引入qwebchannel

/******************************************************************************** Copyright (C) 2016 The Qt Company Ltd.** Copyright (C) 2016 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Milian Wolff <milian.wolff@kdab.com>** Contact: https://www.qt.io/licensing/**** This file is part of the QtWebChannel module of the Qt Toolkit.**** $QT_BEGIN_LICENSE:LGPL$** Commercial License Usage** Licensees holding valid commercial Qt licenses may use this file in** accordance with the commercial license agreement provided with the** Software or, alternatively, in accordance with the terms contained in** a written agreement between you and The Qt Company. For licensing terms** and conditions see https://www.qt.io/terms-conditions. For further** information use the contact form at https://www.qt.io/contact-us.**** GNU Lesser General Public License Usage** Alternatively, this file may be used under the terms of the GNU Lesser** General Public License version 3 as published by the Free Software** Foundation and appearing in the file LICENSE.LGPL3 included in the** packaging of this file. Please review the following information to** ensure the GNU Lesser General Public License version 3 requirements** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.**** GNU General Public License Usage** Alternatively, this file may be used under the terms of the GNU** General Public License version 2.0 or (at your option) the GNU General** Public license version 3 or any later version approved by the KDE Free** Qt Foundation. The licenses are as published by the Free Software** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3** included in the packaging of this file. Please review the following** information to ensure the GNU General Public License requirements will** be met: https://www.gnu.org/licenses/gpl-2.0.html and** https://www.gnu.org/licenses/gpl-3.0.html.**** $QT_END_LICENSE$******************************************************************************/"use strict";var QWebChannelMessageTypes = {signal: 1,propertyUpdate: 2,init: 3,idle: 4,debug: 5,invokeMethod: 6,connectToSignal: 7,disconnectFromSignal: 8,setProperty: 9,response: 10,
};export var QWebChannel = function(transport, initCallback) {if (typeof transport !== "object" || typeof transport.send !== "function") {console.error("The QWebChannel expects a transport object with a send function and onmessage callback property." +" Given is: transport: " + typeof(transport) + ", transport.send: " + typeof(transport.send));return;}var channel = this;this.transport = transport;this.send = function(data) {if (typeof(data) !== "string") {data = JSON.stringify(data);}channel.transport.send(data);}this.transport.onmessage = function(message) {var data = message.data;if (typeof data === "string") {data = JSON.parse(data);}switch (data.type) {case QWebChannelMessageTypes.signal:channel.handleSignal(data);break;case QWebChannelMessageTypes.response:channel.handleResponse(data);break;case QWebChannelMessageTypes.propertyUpdate:channel.handlePropertyUpdate(data);break;default:console.error("invalid message received:", message.data);break;}}this.execCallbacks = {};this.execId = 0;this.exec = function(data, callback) {if (!callback) {// if no callback is given, send directlychannel.send(data);return;}if (channel.execId === Number.MAX_VALUE) {// wrapchannel.execId = Number.MIN_VALUE;}if (data.hasOwnProperty("id")) {console.error("Cannot exec message with property id: " + JSON.stringify(data));return;}data.id = channel.execId++;channel.execCallbacks[data.id] = callback;channel.send(data);};this.objects = {};this.handleSignal = function(message) {var object = channel.objects[message.object];if (object) {object.signalEmitted(message.signal, message.args);} else {console.warn("Unhandled signal: " + message.object + "::" + message.signal);}}this.handleResponse = function(message) {if (!message.hasOwnProperty("id")) {console.error("Invalid response message received: ", JSON.stringify(message));return;}channel.execCallbacks[message.id](message.data);delete channel.execCallbacks[message.id];}this.handlePropertyUpdate = function(message) {message.data.forEach(data => {var object = channel.objects[data.object];if (object) {object.propertyUpdate(data.signals, data.properties);} else {console.warn("Unhandled property update: " + data.object + "::" + data.signal);}});channel.exec({type: QWebChannelMessageTypes.idle});}this.debug = function(message) {channel.send({type: QWebChannelMessageTypes.debug,data: message});};channel.exec({type: QWebChannelMessageTypes.init}, function(data) {for (const objectName of Object.keys(data)) {new QObject(objectName, data[objectName], channel);}// now unwrap properties, which might reference other registered objectsfor (const objectName of Object.keys(channel.objects)) {channel.objects[objectName].unwrapProperties();}if (initCallback) {initCallback(channel);}channel.exec({type: QWebChannelMessageTypes.idle});});
};function QObject(name, data, webChannel) {this.__id__ = name;webChannel.objects[name] = this;// List of callbacks that get invoked upon signal emissionthis.__objectSignals__ = {};// Cache of all properties, updated when a notify signal is emittedthis.__propertyCache__ = {};var object = this;// ----------------------------------------------------------------------this.unwrapQObject = function(response) {if (response instanceof Array) {// support list of objectsreturn response.map(qobj => object.unwrapQObject(qobj))}if (!(response instanceof Object))return response;if (!response["__QObject*__"] || response.id === undefined) {var jObj = {};for (const propName of Object.keys(response)) {jObj[propName] = object.unwrapQObject(response[propName]);}return jObj;}var objectId = response.id;if (webChannel.objects[objectId])return webChannel.objects[objectId];if (!response.data) {console.error("Cannot unwrap unknown QObject " + objectId + " without data.");return;}var qObject = new QObject(objectId, response.data, webChannel);qObject.destroyed.connect(function() {if (webChannel.objects[objectId] === qObject) {delete webChannel.objects[objectId];// reset the now deleted QObject to an empty {} object// just assigning {} though would not have the desired effect, but the// below also ensures all external references will see the empty map// NOTE: this detour is necessary to workaround QTBUG-40021Object.keys(qObject).forEach(name => delete qObject[name]);}});// here we are already initialized, and thus must directly unwrap the propertiesqObject.unwrapProperties();return qObject;}this.unwrapProperties = function() {for (const propertyIdx of Object.keys(object.__propertyCache__)) {object.__propertyCache__[propertyIdx] = object.unwrapQObject(object.__propertyCache__[propertyIdx]);}}function addSignal(signalData, isPropertyNotifySignal) {var signalName = signalData[0];var signalIndex = signalData[1];object[signalName] = {connect: function(callback) {if (typeof(callback) !== "function") {console.error("Bad callback given to connect to signal " + signalName);return;}object.__objectSignals__[signalIndex] = object.__objectSignals__[signalIndex] || [];object.__objectSignals__[signalIndex].push(callback);// only required for "pure" signals, handled separately for properties in propertyUpdateif (isPropertyNotifySignal)return;// also note that we always get notified about the destroyed signalif (signalName === "destroyed" || signalName === "destroyed()" || signalName === "destroyed(QObject*)")return;// and otherwise we only need to be connected only onceif (object.__objectSignals__[signalIndex].length == 1) {webChannel.exec({type: QWebChannelMessageTypes.connectToSignal,object: object.__id__,signal: signalIndex});}},disconnect: function(callback) {if (typeof(callback) !== "function") {console.error("Bad callback given to disconnect from signal " + signalName);return;}object.__objectSignals__[signalIndex] = object.__objectSignals__[signalIndex] || [];var idx = object.__objectSignals__[signalIndex].indexOf(callback);if (idx === -1) {console.error("Cannot find connection of signal " + signalName + " to " + callback.name);return;}object.__objectSignals__[signalIndex].splice(idx, 1);if (!isPropertyNotifySignal && object.__objectSignals__[signalIndex].length === 0) {// only required for "pure" signals, handled separately for properties in propertyUpdatewebChannel.exec({type: QWebChannelMessageTypes.disconnectFromSignal,object: object.__id__,signal: signalIndex});}}};}/*** Invokes all callbacks for the given signalname. Also works for property notify callbacks.*/function invokeSignalCallbacks(signalName, signalArgs) {var connections = object.__objectSignals__[signalName];if (connections) {connections.forEach(function(callback) {callback.apply(callback, signalArgs);});}}this.propertyUpdate = function(signals, propertyMap) {// update property cachefor (const propertyIndex of Object.keys(propertyMap)) {var propertyValue = propertyMap[propertyIndex];object.__propertyCache__[propertyIndex] = this.unwrapQObject(propertyValue);}for (const signalName of Object.keys(signals)) {// Invoke all callbacks, as signalEmitted() does not. This ensures the// property cache is updated before the callbacks are invoked.invokeSignalCallbacks(signalName, signals[signalName]);}}this.signalEmitted = function(signalName, signalArgs) {invokeSignalCallbacks(signalName, this.unwrapQObject(signalArgs));}function addMethod(methodData) {var methodName = methodData[0];var methodIdx = methodData[1];// Fully specified methods are invoked by id, others by name for host-side overload resolutionvar invokedMethod = methodName[methodName.length - 1] === ')' ? methodIdx : methodNameobject[methodName] = function() {var args = [];var callback;var errCallback;for (var i = 0; i < arguments.length; ++i) {var argument = arguments[i];if (typeof argument === "function")callback = argument;else if (argument instanceof QObject && webChannel.objects[argument.__id__] !== undefined)args.push({"id": argument.__id__});elseargs.push(argument);}var result;// during test, webChannel.exec synchronously calls the callback// therefore, the promise must be constucted before calling// webChannel.exec to ensure the callback is set upif (!callback && (typeof(Promise) === 'function')) {result = new Promise(function(resolve, reject) {callback = resolve;errCallback = reject;});}webChannel.exec({"type": QWebChannelMessageTypes.invokeMethod,"object": object.__id__,"method": invokedMethod,"args": args}, function(response) {if (response !== undefined) {var result = object.unwrapQObject(response);if (callback) {(callback)(result);}} else if (errCallback) {(errCallback)();}});return result;};}function bindGetterSetter(propertyInfo) {var propertyIndex = propertyInfo[0];var propertyName = propertyInfo[1];var notifySignalData = propertyInfo[2];// initialize property cache with current value// NOTE: if this is an object, it is not directly unwrapped as it might// reference other QObject that we do not know yetobject.__propertyCache__[propertyIndex] = propertyInfo[3];if (notifySignalData) {if (notifySignalData[0] === 1) {// signal name is optimized away, reconstruct the actual namenotifySignalData[0] = propertyName + "Changed";}addSignal(notifySignalData, true);}Object.defineProperty(object, propertyName, {configurable: true,get: function() {var propertyValue = object.__propertyCache__[propertyIndex];if (propertyValue === undefined) {// This shouldn't happenconsole.warn("Undefined value in property cache for property \"" + propertyName + "\" in object " + object.__id__);}return propertyValue;},set: function(value) {if (value === undefined) {console.warn("Property setter for " + propertyName + " called with undefined value!");return;}object.__propertyCache__[propertyIndex] = value;var valueToSend = value;if (valueToSend instanceof QObject && webChannel.objects[valueToSend.__id__] !== undefined)valueToSend = {"id": valueToSend.__id__};webChannel.exec({"type": QWebChannelMessageTypes.setProperty,"object": object.__id__,"property": propertyIndex,"value": valueToSend});}});}// ----------------------------------------------------------------------data.methods.forEach(addMethod);data.properties.forEach(bindGetterSetter);data.signals.forEach(function(signal) {addSignal(signal, false);});Object.assign(object, data.enums);
}//required for use with nodejs
// if (typeof module === 'object') {
// 	module.exports = {
// 		QWebChannel: QWebChannel
// 	};
// }

2、在main.js引入

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import {QWebChannel} from '../public/js/qwebchannel.js'
import store from './store'
export var qtWebChannel = null;
new QWebChannel(qt.webChannelTransport, (channel) => {qtWebChannel = channel.objects.qtJSBridge;
});
createApp(App).use(store).use(router).mount('#app')

3、在页面中使用

<script setup name="index">
import { qtWebChannel } from "@/main.js";
import { getCurrentInstance, onMounted, reactive, ref } from "vue";
onMounted(() => {let msgType = "loadDataReq";let obj = { msgType };setTimeout(() => {qtWebChannel.sendMessageToJS.connect((response) => {let dataQt = {};if (response) {dataQt = JSON.parse(response);  }   })qtWebChannel.sendMessageToQt(JSON.stringify(obj));}, 1000);
});
</script>

4、router配置

import { createRouter, createWebHashHistory } from 'vue-router'
const routes = [  {path: '/',name: 'index',component: ()=>import('@/views/index/Index')},  
]const router = createRouter({  
//此处只能用hash模式,不然<router-view>里面的东西不能加载history:createWebHashHistory(),routes
})
export default router

5、打包后将资源文件在QT项目中用qrc引入

6、效果图

在这里插入图片描述

注意:
history只能用hash模式,不然里面的东西不能加载

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/5278.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

13_Linux无设备树Platform设备驱动

目录 Linux驱动的分离与分层 驱动的分隔与分离 驱动的分层 platform平台驱动模型简介 platform总线 platform驱动 platform设备 platform设备程序编写 platform驱动程序编写 测试APP编写 运行测试 Linux驱动的分离与分层 像I2C、SPI、LCD 等这些复杂外设的驱动就不…

Fortinet Accelerate 2023·中国区巡展收官丨让安全成就未来

7月18日&#xff0c;2023 Fortinet Accelerate Summit在上海成功举办&#xff01;这亦象征着“Fortinet Accelerate2023中国区巡展”圆满收官。Fortinet携手来自多个典型行业的百余位代表客户&#xff0c;以及Telstra - PBS 太平洋电信、Tenable等多家生态合作伙伴&#xff0c;…

利用数据分析告警机制,实现鸿鹄与飞书双向集成

需求描述 实现鸿鹄与飞书的双向集成&#xff0c;依赖鸿鹄的告警机制&#xff0c;可以发送用户关心的信息到飞书。同时依赖飞书强大的卡片消息功能&#xff0c;在飞书消息里面能够通过链接&#xff08;如下图&#xff09;返回到鸿鹄以方便用户进一步排查和分析问题。 解决方案 1…

CGT Asia嘉年华|2023第四届亚洲细胞与基因治疗 创新峰会(广州站)10月升级启航

近年来&#xff0c;全球CGT发展突飞猛进&#xff0c;为遗传罕见病、难治性慢性病和肿瘤患者带来了新的希望&#xff0c;也成为整个国际领域科技竞争的未来焦点。国家发改委发布的《“十四五”生物经济发展规划》明确指出要重点发展基因诊疗、干细胞治疗、免疫细胞治疗等新技术&…

利用鸿鹄优化共享储能的SCADA 系统功能,赋能用户数据自助分析

摘要 本文主要介绍了共享储能的 SCADA 系统大数据架构&#xff0c;以及如何利用鸿鹄来更好的优化 SCADA 系统功能&#xff0c;如何为用户进行数据自助分析赋能。 1、共享储能介绍 说到共享储能&#xff0c;可能不少朋友比较陌生&#xff0c;下面我们简单介绍一下共享储能的价值…

Python高光谱遥感数据处理与高光谱遥感机器学习方法深度应用

目录 ​第一章 高光谱基础 第二章 高光谱开发基础&#xff08;Python&#xff09; 第三章 高光谱机器学习技术&#xff08;python&#xff09; 第四章 典型案例操作实践 更多推荐 本教程提供一套基于Python编程工具的高光谱数据处理方法和应用案例。 涵盖高光谱遥感的基础…

2023年7月18日,File类,IO流,线程

File类 1. 概述 File&#xff0c;是文件和目录路径的抽象表示 File只关注文件本身的信息&#xff0c;而不能操作文件里的内容 。如果需要读取或写入文件内容&#xff0c;必须使用IO流来完成。 在Java中&#xff0c;java.io.File 类用于表示文件或目录的抽象路径名。它提供了一…

selenium.chrome怎么写扩展拦截或转发请求?

Selenium WebDriver 是一组开源 API&#xff0c;用于自动测试 Web 应用程序&#xff0c;利用它可以通过代码来控制chrome浏览器&#xff01; 有时候我们需要mock接口的返回&#xff0c;或者拦截和转发请求&#xff0c;今天就来实现这个功能。 代码已开源&#xff1a; https:/…

HTML语法

文章目录 前言HTML 文件基本结构常见标签标签种类特殊符号图片链接a链接 双标签链接 列表表格 &#xff1a;表单多行文本域: 前言 HTML是有标签组成的 <body>hello</body>大部分标签成对出现. 为开始标签, 为结束标签. 少数标签只有开始标签, 称为 “单标签”. 开…

Helm 安装prometheus-stack 使用local pv持久化存储数据

目录 背景&#xff1a; 环境准备&#xff1a; 1. 磁盘准备 2. 磁盘分区格式化 local storage部署 1. 节点打标签 2. 创建local pv storageClass和prometheus-pv Prometheus-stack部署 1. 下载helm chart包 2. values.yaml 参数解释 3. 部署prometheus-stack 4. 查看…

Baichuan-13B:130亿参数的开源语言模型,引领中文和英文benchmark

Baichuan-13B: 一个强大的开源大规模语言模型 标题&#xff1a;Baichuan-13B&#xff1a;130亿参数的开源语言模型&#xff0c;引领中文和英文benchmark Baichuan-13B是由百川智能开发的一个开源大规模语言模型项目&#xff0c;包含了130亿参数。该模型在中文和英文的权威ben…

【广州华锐互动】VR地铁消防逃生路线演练系统

随着城市轨道交通的不断发展&#xff0c;事故应急演练的重要性也越来越受到重视。而VR技术的应用&#xff0c;为地铁消防逃生路线演练带来了许多亮点&#xff0c;包括以下几个方面&#xff1a; 首先&#xff0c;VR技术可以提供高度真实的模拟场景。在传统的事故应急演练中&…

ipad可以使用其他品牌的手写笔吗?平价ipad手写笔推荐

我是一个拥有多年数码经验的爱好者&#xff0c;我知道一些关于电容笔的知识。我认为&#xff0c;苹果原装的电容笔与普通的电容笔最大的不同之处&#xff0c;就是其所带来的压感不同。由于“重力压感”的特殊性&#xff0c;我们能很快地把色彩填充到画面中。除此之外&#xff0…

亿发软件:数字化大中型制造企业生产管理应用,实现智慧工厂信息化

随着信息技术与制造业的深度协调&#xff0c;作为企业发展的趋势&#xff0c;大中型制造企业需要拥抱信息化建设。通过运用信息技术和数字化运营&#xff0c;大中型制造企业的生产、设计、经营、管理、后续服务等都实现自动化、智能化。大中型制造企业信息化建设解决方案&#…

uniapp中axios封装和环境配置

axios版本 最好锁定版本&#xff0c;避免bug axios-miniprogram-adapter这个依赖主要是适配小程序网络请求的适配器&#xff0c;为了解决uniapp 适配axios请求&#xff0c;避免报adapter is not a function错误 cnpm i axios0.26.0 axios-miniprogram-adapter 配置adapter函…

bean的生命周期

生命周期&#xff1a;从生到死的过程。那么对于bean来说就是从创建到销毁的过程。 普通的Java对象的创建由我们new创建&#xff0c;然后在不用的时候&#xff0c;java回收机制会自动回收。那么bean呢&#xff1f; bean是spring中的对象&#xff0c;和普通对象不一样的就是bea…

Unity游戏源码分享-Unity手游火柴忍者游戏StickmanDojo

Unity游戏源码分享-Unity手游火柴忍者游戏StickmanDojo 项目地址&#xff1a;https://download.csdn.net/download/Highning0007/88050234

蒲公英打包环境搭建碰到问题

一&#xff1a;证书那边选择手动&#xff0c;不要自动&#xff0c;——》debug配置dev证书&#xff0c;release配置ad-hoc证书 二&#xff1a;证书有时候不生效&#xff0c;删除重新下载。~/Library/MobileDevice/Provisioning Profiles 三&#xff1a;更新测试手机时&#…

OpenCv色彩空间

目录 一、RGB 二、图像处理入门 三、色彩空间的转换 一、RGB 在表示图像时&#xff0c;有多种不同的颜色模型&#xff0c;但最常见的是红、绿、蓝(RGB) 模型RGB 模型是一种加法颜色模型&#xff0c;其中原色 (在RGB模型中&#xff0c;原色是红色 R、绿色 G 和蓝色 B)混合在…

设计模式之享元模式

写在前面 本文看下一种结构型设计模式&#xff0c;享元模式。 1&#xff1a;介绍 1.1&#xff1a;什么时候使用享元模式 当程序需要大量的重复对象&#xff0c;并且这些大量的重复对象只有部分属性不相同&#xff0c;其他都是相同的时候&#xff0c;就可以考虑使用享元设计…