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/343.shtml

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

相关文章

记录--再也不用手动改package.json的版本号

这里给大家分享我在网上总结出来的一些知识&#xff0c;希望对大家有所帮助 本文的起因是有在代码仓库发包后&#xff0c;同事问我“为什么package.json 里的版本还是原来的&#xff0c;有没有更新&#xff1f;”&#xff0c;这个时候我意识到&#xff0c;我们完全没有必要在每…

阿里云无影云电脑具体价格_云桌面不同配置1元报价

阿里云无影云电脑配置费用&#xff0c;4核8G企业办公型云电脑可以免费使用3个月&#xff0c;无影云电脑地域不同费用不同&#xff0c;无影云电脑是由云桌面配置、云盘、互联网访问带宽、AD Connector、桌面组共用桌面session等费用组成&#xff0c;阿里云百科分享阿里云无影云电…

什么是分布式软件系统

:什么是分布式软件系统&#xff1f;分布式软件系统是什么意思&#xff1f; 分布式软件系统(Distributed Software Systems)是支持分布式处理的软件系统,是在由通信网络互联的多处理机体系结构上执行任务的系统。它包括分布式操作系统、分布式程序设计语言及其编译(解释)系统、分…

Unity 2D骨骼动画+IK反向动力学

本文言简意赅的完成这个流程&#xff0c;废话不多说&#xff01;干&#xff01; 等等&#xff0c;先看看效果 第一步&#xff1a;导入2D Animation包 当前环境&#xff1a;Unity3D 2021(不需要完全一样也可以) 进入unity后点击Window->PackageManager打开如下界面 按Insta…

LangChain 联合创始人下场揭秘:如何用 LangChain 和向量数据库搞定语义搜索?

近期&#xff0c;关于 ChatGPT 的访问量有所下降的消息引发激烈讨论&#xff0c;不过这并不意味着开发者对于 AIGC 的热情有所减弱&#xff0c;例如素有【2023 最潮大语言模型 Web 开发框架】之称的大网红 LangChain 的热度就只增不减。 原因在于 LangChain 作为大模型能力“B2…

Vue3_简介、CompositionVPI、新的组件

文章目录 Vue3快速上手1.Vue3简介2.Vue3带来了什么1.性能的提升2.源码的升级3.拥抱TypeScript4.新的特性 一、创建Vue3.0工程1.使用 vue-cli 创建2.使用 vite 创建 二、常用 Composition API1.拉开序幕的setup2.ref函数3.reactive函数4.Vue3.0中的响应式原理vue2.x的响应式Vue3…

万字长文 | Hadoop 上云: 存算分离架构设计与迁移实践

一面数据原有的技术架构是在线下机房中使用 CDH 构建的大数据集群。自公司成立以来&#xff0c;每年都保持着高速增长&#xff0c;业务的增长带来了数据量的剧增。 在过去几年中&#xff0c;我们按照每 1 到 2 年的规划扩容硬件&#xff0c;但往往在半年之后就不得不再次扩容。…

《Redis 核心技术与实战》课程学习笔记(八)

String 类型为什么不好用了&#xff1f; String 类型可以保存二进制字节流&#xff0c;只要把数据转成二进制字节数组&#xff0c;就可以保存了。String 类型并不是适用于所有场合的&#xff0c;它有一个明显的短板&#xff0c;就是它保存数据时所消耗的内存空间较多。 为什么…

Unity Shader - SV_POSITION 和 TEXCOORD[N] 的varying 在 fragment shader 中输出的区别

起因 因另一个TA同学问了一个问题 我抱着怀疑的心态&#xff0c;测试了一下 发现 varying 中的 sv_position 和 texcoord 的值再 fragment shader 阶段还真的不一样 而且 sv_position 还不是简单的 clipPos/clipPos.w 的操作 因此我自己做了一个试验&#xff1a; 结果还是不一…

电脑应用程序发生异常怎么办?

有时候我们打开电脑上面的某个软件时&#xff0c;会打不开&#xff0c;并且会弹出如下的错误提示“应用程序发生异常 未知的软件异常&#xff08;&#xff58;&#xff58;&#xff58;&#xff09;&#xff0c;位置为&#xff58;&#xff58;”。相信大多数的人在使用电脑的时…

Pytorch基本使用—激活函数

✨1 介绍 ⛄ 1.1 概念 激活函数是神经网络中的一种数学函数&#xff0c;它被应用于神经元的输出&#xff0c;以决定神经元是否应该被激活并传递信号给下一层。常见的激活函数包括Sigmoid函数、ReLU函数、Tanh函数等。 &#x1f384; 1.2 性质 激活函数是神经网络中的一种重…

为什么单片机可以直接烧录程序的原因是什么?

单片机&#xff08;Microcontroller&#xff09;可以直接烧录程序的原因主要有以下几点&#xff1a; 集成性&#xff1a;单片机是一种高度集成的芯片&#xff0c;内部包含了处理器核心&#xff08;CPU&#xff09;、存储器&#xff08;如闪存、EEPROM、RAM等&#xff09;、输入…

校园wifi网页认证登录入口

很多校园wifi网页认证登录入口是1.1.1.1 连上校园网在浏览器写上http://1.1.1.1就进入了校园网 使 用 说 明 一、帐户余额 < 0.00元时&#xff0c;帐号被禁用&#xff0c;需追加网费。 二、在计算中心机房上机的用户&#xff0c;登录时请选择新建帐号时给您指定的NT域&…

windows 搭建ssh服务

1、官网下载安装包&#xff1a;mls-software.com 2、点击安装&#xff08;一直默认即可&#xff09; 3、配置 opensshServer 4、成功登录

Python深度强化学习实战 ——OpenAI Gym-CarRacing自动驾驶项目

&#x1f4ad; 写在前面&#xff1a;本篇是关于 OpenAI Gym-CarRacing 自动驾驶项目的博客&#xff0c;面向掌握 Python 并有一定的深度强化学习基础的读者。GYM-Box2D CarRacing 是一种在 OpenAI Gym 平台上开发和比较强化学习算法的模拟环境。它是流行的 Box2D 物理引擎的一个…

灌区信息化智能测控一体化闸门系统解决方案

一、方案背景 闸门是节水灌溉工程中重要组成部分。在农田灌区中&#xff0c;一方面存在传统手摇闸门&#xff0c;未能实现自动化、数字化&#xff0c;另一方面部分灌区闸站虽然部分实现了自动化控制&#xff0c;但是由于闸站较多&#xff0c;有些位置较为偏僻&#xff0c;部分水…

Jmeter接口关联(一)【使用json层级方式提取值】与python中使用层级方式提取值 完成接口关联

文章目录 前言一、按照 json 的路径来提取 ​​​​​​​&#xff08;1&#xff09;成功匹配到数据的案例&#xff08;按照层级匹配&#xff09;&#xff08;2&#xff09;失败未匹配到数据的案例&#xff08;没有按照层级匹配&#xff09;json提取器二、使用完整的接口关联&a…

selenium自动化测试工具

Selenium是一个用于测试网站的自动化测试工具&#xff0c;支持各种浏览器包括Chrome、Firefox、Safari等主流界面浏览器&#xff0c;同时也支持phantomJS无界面浏览器。 查看chrome版本&#xff0c;114.05735.199 去 http://chromedriver.storage.googleapis.com/index.html 网…

密码学证明方案寒武纪大爆发——扩容、透明性和隐私的变革潜力

1. 引言 前序博客有&#xff1a; ZKP大爆炸 本文主要参考&#xff1a; StarkWare 2023年6月博客 Cambrian Explosion of Cryptographic Proofs----The transformative potential for scalability, transparency, and privacy2023年3月Eli Ben-Sasson在The 13th BIU Winter …

nginx页面优化与防盗链

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 一、nginx页面优化1.版本号1.1 查看版本号1.2 修改版本号1.2.1 修改配置文件1.2.2 修改源码文件&#xff0c;重新编译安装 2.nginx的日志分割3.nginx的页面压缩3.1 …