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 directly
			channel.send(data);
			return;
		}
		if (channel.execId === Number.MAX_VALUE) {
			// wrap
			channel.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 objects
		for (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 emission
	this.__objectSignals__ = {};

	// Cache of all properties, updated when a notify signal is emitted
	this.__propertyCache__ = {};

	var object = this;

	// ----------------------------------------------------------------------

	this.unwrapQObject = function(response) {
		if (response instanceof Array) {
			// support list of objects
			return 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-40021
				Object.keys(qObject).forEach(name => delete qObject[name]);
			}
		});
		// here we are already initialized, and thus must directly unwrap the properties
		qObject.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 propertyUpdate
				if (isPropertyNotifySignal)
					return;

				// also note that we always get notified about the destroyed signal
				if (signalName === "destroyed" || signalName === "destroyed()" || signalName === "destroyed(QObject*)")
					return;

				// and otherwise we only need to be connected only once
				if (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 propertyUpdate
					webChannel.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 cache
		for (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 resolution
		var invokedMethod = methodName[methodName.length - 1] === ')' ? methodIdx : methodName

		object[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__
					});
				else
					args.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 up
			if (!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 yet
		object.__propertyCache__[propertyIndex] = propertyInfo[3];

		if (notifySignalData) {
			if (notifySignalData[0] === 1) {
				// signal name is optimized away, reconstruct the actual name
				notifySignalData[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 happen
					console.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模式,不然里面的东西不能加载

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

MobPush Android For Unity

本文档以unity2020.3.41演示 集成准备 注册账号 使用MobSDK之前&#xff0c;需要先在MobTech官网注册开发者账号&#xff0c;并获取MobTech提供的AppKey和AppSecret&#xff0c;详情可以点击查看注册流程 下载.unitypackage包 打开 Github 下载 MobPush-For-Unity 项目&am…

java项目之贝儿米幼儿教育管理系统(ssm+mysql+jsp)

风定落花生&#xff0c;歌声逐流水&#xff0c;大家好我是风歌&#xff0c;混迹在java圈的辛苦码农。今天要和大家聊的是一款基于ssm的贝儿米幼儿教育管理系统。技术交流和部署相关看文章末尾&#xff01; 开发环境&#xff1a; 后端&#xff1a; 开发语言&#xff1a;Java…

队列的表示和操作

队列&#xff1a;队列是仅在表尾进行插入操作&#xff0c;在表头进行删除操作的线性表。 表尾即an端&#xff0c;称为队尾&#xff0c;表头即a1端&#xff0c;称为队头。 队列的存储方式&#xff1a;顺序队列和链式队列 队列顺序表示 #define MAXQSIZE 100 //最大队列长度 …

使用php数组实现双色球的随机选号

一、双色球彩票介绍 双色球是中国福利彩票的一种常见玩法&#xff0c;也是全国彩民最爱的彩种之一。玩法规则是在33个红色球中选择6个数字&#xff0c;在16个蓝色球中选择1个数字&#xff0c;红色球号码区间为1-33&#xff0c;蓝色球号码区间为1-16。可以单式投注或者复式投注…

Python对Excel不同的行分别复制不同的次数

本文介绍基于Python语言&#xff0c;读取Excel表格文件数据&#xff0c;并将其中符合我们特定要求的那一行加以复制指定的次数&#xff0c;而不符合要求的那一行则不复制&#xff1b;并将所得结果保存为新的Excel表格文件的方法。 这里需要说明&#xff0c;在我们之前的文章Pyt…

Python爬虫——urllib_post请求百度翻译

post请求&#xff1a; post的请求参数&#xff0c;是不会拼接在url后面的&#xff0c;而是需要放在请求对象定制的参数中 post请求的参数需要进行两次编码&#xff0c;第一次urlencode&#xff1a;对字典参数进行Unicode编码转成字符串&#xff0c;第二次encode&#xff1a;将字…

【ArcGIS微课1000例】0070:制作宾馆酒店分布热度热力图

本文讲解在ArcGIS中,基于长沙市酒店宾馆分布矢量点数据(POI数据)绘制酒店分布热力图。 相关阅读: 【GeoDa实用技巧100例】004:绘制长沙市宾馆热度图 【ArcGIS Pro微课1000例】0028:绘制酒店分布热力图(POI数据) 文章目录 一、加载宾馆分布数据二、绘制热度图一、加载宾…

机器学习(十六):决策树

全文共18000余字&#xff0c;预计阅读时间约36~60分钟 | 满满干货&#xff0c;建议收藏&#xff01; 一、介绍 树模型是目前机器学习领域最为重要的模型之一&#xff0c;同时它也是集成学习中最常用的基础分类器。 与线性回归、逻辑回归等算法不同&#xff0c;树模型并不只是…

Web3.0:重新定义数字资产的所有权和交易方式

随着区块链技术的发展和应用&#xff0c;数字资产的概念已经逐渐深入人心。数字资产不仅包括加密货币&#xff0c;还包括数字艺术品、虚拟土地、游戏道具等各种形式的数字物品。然而&#xff0c;在传统的互联网环境下&#xff0c;数字资产的所有权和交易方式往往受到限制和约束…

Java 常用的重构技巧指南 v1.0

前段时间&#xff0c;leader 在 review 代码的时候发现了代码中 存在的一部分的问题&#xff0c;导致 代码的复杂度太高了&#xff0c;包括大部分的sql 都是属于慢sql &#xff0c;还是在建立了索引的情况下 , 代码的流程过于臃肿&#xff0c;而且本人编码的习惯&#xff0c;习…

Zookeeper集群 + Kafka集群 + Filebeat + ELK

目录 一&#xff1a;Zookeeper 概述 1、Zookeeper 定义 2、Zookeeper 工作机制 3、Zookeeper 特点 4、 Zookeeper 数据结构 5、 Zookeeper 应用场景 6、 Zookeeper 选举机制 &#xff08;1&#xff09;第一次启动选举机制 &#xff08;2&#xff09;非第一次启动选举机制…

如何快速爬取国内985大学学术学报pdf文件

背景 最近&#xff0c;在爬取关于国内985大学的学报时&#xff0c;我注意到大部分大学学报站点格式都采用相似的形式&#xff0c;并且PDF链接都使用自增的ID。然而&#xff0c;我也发现了一个问题&#xff0c;即大多数PDF链接的ID并不是连续的。现在我将向你分享一些方法&…

数据结构(王道)——线性表的存储结构之链表存储

线性表的链表存储&#xff1a; 一、单链表定义&#xff1a; 用代码定义一个单链表&#xff1a; 不带头结点的单链表定义&#xff1a; 带头结点的单链表定义&#xff1a; 单链表定义总结&#xff1a; 二、单链表的基本操作&#xff08;插入删除查找&#xff09; 1、插入 如何在…

普华(Autosar OS开发)第一部分

普华灵智基础软件平台产品手册 一、基本情况 普华基础软件自2009年起深耕AUTOSAR车用基础软件领域,作为AUTOSAR组织高级合作伙伴,拥有强大的AUTOSAR专业技术团队。普华基础软件为国内各大OEM整车厂和主要的零部件供应商提供基于AUTOSAR标准的国产化汽车电子基础软件平台、开…

RocketMQ第四节(部署模式、监控面板等)

1&#xff1a;mq的部署模式 部署方式 | RocketMQ 参考官网。 单机模式&#xff1a;抗风险能力差&#xff0c;单机挂机没服务&#xff0c;单机硬盘损坏&#xff0c;丢失数据 多机&#xff08;多master没有Slave副本&#xff09;: 多个master采用RAID10磁盘&#xff0c;不会丢…

STM32单片机示例:多个定时器同步触发启动

文章目录 前言基础说明关键配置与代码其它补充示例链接 前言 多个定时器同步触发启动是一种比较实用的功能&#xff0c;这里将对此做个示例说明。 基础说明 该示例演示通过一个TIM使能时同步触发使能另一个TIM。 本例中使用TIM1作为主机&#xff0c;使用TIM1的使能信号作为…

怎样优雅地增删查改(五):按组织架构查询

文章目录 原理实现应用测试 之前我们实现了Employee&#xff0c;Alarm管理模块以及通用查询应用层。 Employee的集合查询业务&#xff0c;是通过重写CreateFilteredQueryAsync方法&#xff0c;来实现按组织架构查询的过滤条件。 我们将这段逻辑代码提取到通用查询应用层中&…

数据结构--图的存储 十字链表、邻接多重表

数据结构–图的存储 十字链表、邻接多重表 十字链表存储有向图 空间复杂度&#xff1a;O(|V||E|) 如何找到指定顶点的所有出边&#xff1f;——顺着绿色线路找 如何找到指定顶点的所有入边&#xff1f;——顺着橙色线路找 注意&#xff1a;十字链表只用于存储有向图 \color{re…

xss跨站脚本攻击总结

XSS(跨站脚本攻击) 跨站脚本攻击&#xff08;Cross Site Scripting&#xff09;&#xff0c;为了不和层叠样式表&#xff08;Cascading Style Sheets &#xff09;CSS的缩写混淆&#xff0c;故将跨站脚本攻击缩写为XSS。恶意攻击者往Web页面里插入恶意Script代码&#xff0c;当…

力扣 332. 重新安排行程

一、题目描述 给你一份航线列表 tickets&#xff0c;其中 tickets[i] [fromi, toi] 表示飞机出发和降落的机场地点。请你对该行程进行重新规划排序。 所有这些机票都属于一个从 JFK&#xff08;肯尼迪国际机场&#xff09;出发的先生&#xff0c;所以该行程必须从 JFK 开始。…