qt和vue的交互

news2024/11/20 3:33:38

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模式,不然里面的东西不能加载

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

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

相关文章

简易评分系统

目录 一、实验目的 二、操作环境 三、实验内容和过程 1.实验内容 2.代码 2.1 用户验证功能 2.2 菜单函数 2.3 评分功能 四、结果分析 总体的输出结果&#xff1a; 保存文件成功截图&#xff1a; 五、小结 一、实验目的 1.巩固和提高学生学过的基础理论和专业知识&am…

windows下安装consul、springboot整合consul

Spring Cloud Consul通过自动配置和绑定到Spring Environment和其他Spring编程模型习语&#xff0c;为Spring Boot应用程序提供Consul集成。通过一些简单的注解&#xff0c;可以快速启用和配置应用程序内的常用模式&#xff0c;并使用Hashicorp的Consul构建大型分布式系统。提供…

使用Dreambooth LoRA微调SDXL 0.9

本文将介绍如何通过LoRA对Stable Diffusion XL 0.9进行Dreambooth微调。DreamBooth是一种仅使用几张图像(大约3-5张)来个性化文本到图像模型的方法。 本教程基于通过LoRA进行Unet微调&#xff0c;而不是进行全部的训练。LoRA是在LoRA: Low-Rank Adaptation of Large Language …

如何通过CRM系统减低客户流失率并提高销售业绩?

销售人员如何提高业绩&#xff0c;减低客户流失率&#xff1f;通过CRM客户管理系统与客户建立良好的客户关系、提升客户体验助力销售人员业绩节节攀升&#xff0c;降低客户流失率。接下来我们就来说一说CRM系统如何实现的&#xff1f; 1.全渠道沟通提升客户体验 只有足够多的…

搜索结果处理

1、排序 #sort排序 GET /hotel/_search {"query": {"match_all": {}},"sort": [{"score": "desc"},{"price": "asc"}] }#找到121.6&#xff0c;31周围的酒店&#xff0c;距离升序排序 GET /hotel/_sea…

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

深入对象 创建对象三种方式 构造函数 小练习 <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta http-equiv"X-UA-Compatible" content"IEedge"><meta name"viewport"…

python_openpyxl常用语法记录

目录 写在前面&#xff1a; 开始 工作薄 and 工作表 操作单元格 访问&#xff08;调用&#xff09;单个单元格 访问&#xff08;调用&#xff09;多个单元格 保存工作薄 用例 例&#xff1a;简单数据和条形图 操作样式 样式的默认值 单元格样式和命名样式 单元格样…

配置Hadoop_0

配置Hadoop_0 1配置Hadoop100模板虚拟机1.1配置Hadoop100模板虚拟机硬件1.2配置Hadoop100模板虚拟机软件1.3配置Hadoop100模板虚拟机IP地址1.4配置Hadoop100模板虚拟机主机名称/主机名称映射1.5配置Hadoop100模板虚拟机远程操作工具 1配置Hadoop100模板虚拟机 Hadoop100 内存…

编译给IOS平台用的liblzma库(xz与lzma)

打开官方网: XZ Utils 新工程仓库: git clone https://git.tukaani.org/xz.git git clone https://github.com/tukaani-project/xz 旧工程仓库: git clone https://git.tukaani.org/lzma.git 旧版本工程编译: 先进行已下载好的lzma目录 执行./autogen.sh生成configure配置…

233. 数字 1 的个数

题目描述&#xff1a; 主要思路&#xff1a; 寻找1的个数主要分为两个部分&#xff1a;完整的1和取余的1。 完整的1&#xff1a;从个位一直到最高位&#xff0c;例如十位上的1可以出现10次&#xff0c;10-19&#xff0c;然后看他的高位&#xff0c;看看可以出现几轮循环。 取余…

QListWidget 小节

QListWidget 小节 QListWidget 简介举例UI设计头文件源文件 QListWidget 简介 以下是 QListWidget 常用函数的一些说明&#xff1a; addItem(item)&#xff1a;向列表中添加一个项。 addItems(items)&#xff1a;向列表中添加多个项。 clear()&#xff1a;清空列表中的所有项…

射线与物质的相互作用

射线与物质的相互作用 射线与物质的相互作用概要 电离——核外层电子克服束缚成为自由电子&#xff0c;原子成为正离子激发——使核外层电子由低能级跃迁到高能级而使原子处于激发状态&#xff0c;退激发光 射线 致电离辐射 慢化 电离损失&#xff1a;带电粒子与靶物质原子…

this指针/闭包及作用域

一.作用域链 1.通过一个例子 let aglobalconsole.log(a);//globalfunction course(){let bjsconsole.log(b);//jssession()function session(){let cthisconsole.log(c);//Windowteacher()//函数提升function teacher(){let dstevenconsole.log(d);//stevenconsole.log(test1,…

【unity之IMGUI实践】单例模式管理数据存储【二】

&#x1f468;‍&#x1f4bb;个人主页&#xff1a;元宇宙-秩沅 &#x1f468;‍&#x1f4bb; hallo 欢迎 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! &#x1f468;‍&#x1f4bb; 本文由 秩沅 原创 &#x1f468;‍&#x1f4bb; 收录于专栏&#xff1a;uni…

FocusState, SubmitTextField 的使用

1. FocusState 输入文本添加焦点状态 1.1 实现 /// 输入文本焦点状态 struct FocusStateBootcamp: View {// 使用枚举enum OnboardingFields: Hashable{case usernamecase password}//FocusState private var usernameInFocus: BoolState private var username: String "…

两分钟python发个邮件

python简单发个邮件 直接上代码测试 之前spring boot简单发送发送个邮件大约5min&#xff0c;ennn这个python发个邮件两三分钟吧 直接上代码 import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMETextclass MailTest(object):def…

Flink 在新能源场站运维的应用

摘要&#xff1a;本文整理自中南电力设计院工程师、注册测绘师姚远&#xff0c;在 Flink Forward Asia 2022 行业案例专场的分享。本篇内容主要分为四个部分&#xff1a; 1. 建设背景 2. 技术架构 3. 应用落地 4. 后续及其他 Tips&#xff1a;点击「阅读原文」免费领取 5000CU*…

Vue localhost 从 http 307 到 https

Vue localhost 从 http 307 到 https HTTP 307 与 HSTS HTTP 307中间人攻击HSTS - HTTP Strict Transport Security 如何解决问题 Vue localhost 从 http 307 到 https 一个 Vue2 项目之前本地都是通过 HTTP 的 localhost 访问(如下) 后来突然无法访问了, 提示的错误内容是 E…

静电接地桩的设计和施工

静电接地桩是用于将静电荷引导到地下的装置&#xff0c;以确保工作环境。以下是一般静电接地桩设计的一些建议和步骤&#xff1a; 1. 选择合适的位置&#xff1a;静电接地桩应该位于静电产生源附近&#xff0c;并接近地面。可以选择在室内或室外&#xff0c;但要确保容易维护和…

web中引入live2d的moc3模型

文章目录 前言下载官方sdk文件使用ide编译项目&#xff08;vsCode&#xff09;项目初始化使用vsCode项目树介绍使用live server运行index页面 演示导入自己的模型并显示modelDir文件resources文件夾案例模型修改modelDir然後重新打包項目運行 前言 先跟着官方sdk调试一遍&…