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.hqwc.cn/news/27387.html

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

相关文章

APP加固:助力移动应用安全合规

近日&#xff0c;工业和信息化部发布了2023年第2批侵害用户权益行为的App&#xff08;SDK&#xff09;名单&#xff0c;55款App因涉及强制、频繁、过度索取权限等问题而被通报。这一举措进一步凸显了合规对于APP发展的重要性。 根据工业和信息化部的通报&#xff0c;被通报的这…

Vue3统计数值(Statistic)

可自定义设置以下属性&#xff1a; 数值的标题&#xff08;title&#xff09;&#xff0c;类型&#xff1a;string | slot&#xff0c;默认&#xff1a;‘’数值的内容&#xff08;value&#xff09;&#xff0c;类型&#xff1a;string | number&#xff0c;默认&#xff1a;…

【程序人生】如何在工作中保持稳定的情绪?

前言 在工作中保持稳定的情绪是现代生活中一个备受关注的话题。随着职场压力和工作挑战的增加&#xff0c;我们常常发现自己情绪波动不定&#xff0c;甚至受到负面情绪的困扰。然而&#xff0c;保持稳定的情绪对于我们的工作效率、人际关系和整体幸福感都至关重要。 无论你是…

Delete `␍`eslint(prettier/prettier)报错的终极解决方案

1.背景 在进行代码仓库clone打开后&#xff0c;vscode报错全屏的 Delete ␍eslint(prettier/prettier)问题 原因是因为&#xff1a; 罪魁祸首是git的一个配置属性&#xff1a; 由于历史原因&#xff0c;windows下和linux下的文本文件的换行符不一致。* Windows在换行的时候&…

Spring 框架——事件驱动模型

目录 1.概述2.三种角色2.1.事件角色2.2.事件监听者角色2.3.事件发布者角色 3.示例 1.概述 &#xff08;1&#xff09;Spring 事件驱动模型是 Spring 框架中的一种编程模型&#xff0c;也被称为发布/订阅模型&#xff0c;通过使用观察者模式和事件机制&#xff0c;实现了组件之…

优化CSS重置过程:探索CSS层叠技术的应用与优势

目录 下面是正文~~ CSS重置方法 方法的结合 合并方法的问题 通用移除样式 顺序很重要 CSS 优先级 我们的CSS特异性冲突 CSS Layers 来拯救 Sass 预处理器支持 浏览器支持 总结 这篇文章介绍了一种名为CSS层叠的技术&#xff0c;用于优化CSS重置过程。它解释了CSS重…

re学习(18)[ACTF新生赛2020]rome1(Z3库+window远程调试)

参考视频: Jamiexu793的个人空间-Jamiexu793个人主页-哔哩哔哩视频 代码分析&#xff1a; 其主要内容在两个while循环中&#xff08;从定义中可知flag位16个字符&#xff09;。 看第二个循环&#xff0c;可知是比较result和经过第一个循环得到的v1比较&#xff08;就是flag…

免费使用Elasticsearch官网15天

注册登录 点击创建索引时候会给你展示一个密钥。这个密钥就是你的用户密码 如下图 你的服务地址大致样式如下 https://huihai.es.us-central1.gcp.cloud.es.io 这里需要你输入用户密码,上面图4&#xff08;图中&#xff09;&#xff0c;下载时候的用户密码 登录完成 这样就能…

使用docker的常见bug

BUG1&#xff1a;磁盘被占满导致docker无法使用 docker ps 【查看docker能否正常使用】 正常的话会打印下图信息: 不正常的话打印如下图信息&#xff1a; journalctl -u docker 【查看docker无法正常使用的原因】&#xff0c;本次测试中遇到下图bug&#xff0c;意思是/var/l…

Flutter 跳转应用市场评分——超简洁实现

最近在做flutter跳转去应用市场评分的功能&#xff0c;虽然是一个很小的功能&#xff0c;但是要做的既简单又高效&#xff0c;同时又能把细节考虑到&#xff0c;还是有坑要走的&#xff0c;这边记录一下。 背景 做应用市场相关的运营&#xff0c;在app内增加评分引导&#xf…

前端学习——JS进阶 (Day3)

编程思想 面向过程编程 面向对象编程 (oop) 构造函数 <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta http-equiv"X-UA-Compatible" content"IEedge"><meta name"viewport…

python+allure+jenkins

目录 前言 在 python 中使用 allure 1. 安装 pytest 2. 安装 pytest-allure-adaptor 3. 使用 pytest 执行测试用例并生成 allure 中间报告&#xff08;此步骤可以省略&#xff0c;因为在 jenkins job 中会配置执行类似的命令&#xff09; 4. Jenkins 中安装Allure Jenkin…