qt和vue交互

news2024/11/26 14:55:10

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/765452.html

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

相关文章

Cisco学习笔记(CCNA)——Introduction to TCP/IP

Introduction to TCP/IP 常见协议 应用层协议 协议 端口号 描述 HTTP 80 超文本传输协议&#xff0c;提供浏览网页服务 Telnet 23 远程登录协议&#xff0c;提供远程管理服务 FTP 20、21 文件传输协议&#xff0c;提供互联网文件资源共享服务 SMTP 25 简单邮件传…

【个人笔记】Linux登录时要执行的文件与内建命令

Linux登录时要执行的文件 在刚登录Linux时&#xff0c;首先启动 /etc/profile 文件&#xff0c;然后再启动用户目录下的 ~/.bash_profile、 ~/.bash_login或 **/.profile**文件中的其中一个&#xff0c;执行的顺序为&#xff1a;/.bash_profile、 ~/.bash_login、 ~/.profile。…

使用基于自动化生成式 AI 的 Ansible-Lightspeed 服务高效开发 Ansible Playbook(附视频)

《OpenShift / RHEL / DevSecOps 汇总目录》 自动化生成式 AI 的 Ansible-Lightspeed 服务核心功能 Ansible-Lightspeed 是 RedHat 提供的一项自动化生成式 AI 的服务&#xff0c;它可以帮助 Ansible 开发人员更快、更好地开发 Playbook。除了自动生成 Playbook 内容外&#…

直播回顾|用户增长之路,如何兼具体验和点击率?

激活用户的关键在于深入理解产品功能、引导用户体验产品的核心价值。在这方面&#xff0c;推送功能就是简单而便捷的解决方案之一。通过推送活动和优惠消息&#xff0c;吸引用户点击&#xff0c;进而提升用户参与度和留存率。 在推送消息的过程中&#xff0c;我们可能会遇到这…

ROS节点通信Demo

0 开始之前 确保你已经安装了ROS (Robot Operating System)。 1 第一步&#xff1a; 创建一个ROS包 在开始编程前&#xff0c;我们首先创建一个新的ROS包(package)。移动到你的catkin workspace的 src 文件夹下&#xff0c;然后运行以下命令&#xff1a; cd ~/catkin_ws/sr…

linux之Ubuntu系列(二)远程管理指令 putty Xshell

shutdown shutdown 选项 时间 关机或重启 选项&#xff1a; -r 重新启动 提示 不指定选项和参数&#xff0c;默认表示1分钟之后 关闭电脑用SSH远程维护服务器时&#xff0c;最好不要关闭系统&#xff0c;而应该重新启动系统 -r shutdown常用示例 # 1分钟后关机 shutdown …

LayUI之增删改查

目录 一、前言 1.1 前言 1.2 前端代码(数据表格组件) 1.3 封装JS 二、LayUI增删改查的后台代码 2.1 编写Dao方法 2.1 增加 2.2 删除 2.3 修改 三、LayUI增删改查的前端代码 3.1 增加 一、前言 1.1 前言 上一篇文章我们一起做了LayUI的动态添加选项卡&#xff0c;这一篇…

uniapp基于阿里图标库引入彩色的图标iconfont

1.进入阿里巴巴矢量图标库链接: https://www.iconfont.cn/&#xff0c;添加图标到项目&#xff0c;然后下载至本地 2.对下载的文件进行解压&#xff0c;命令行进入解压后的文件下&#xff0c;执行一下命令&#xff0c;全局安装iconfont-tools工具 npm install -g iconfont-to…

SqlSerer数据库【进阶】

六、约束 &#xff08;1&#xff09;主键约束 1.单一主键 格式: alter table 表名 add constraint 主键名 primary key (列名) go例子: alter table t_student add constraint pk_t_student primary key (stud_id) go注意:在建表的时候主键不能为空 2.复合主键 复合主键…

基于小波哈尔法(WHM)的一维非线性IVP测试问题的求解(Matlab代码实现)

&#x1f4a5;1 概述 小波哈尔法&#xff08;WHM&#xff09;是一种求解一维非线性初值问题&#xff08;IVP&#xff09;的数值方法。它基于小波分析的思想&#xff0c;通过将原始问题转化为小波空间中的线性问题&#xff0c;然后进行求解。以下是一维非线性IVP测试问题的求解…

2023年郑州/杭州/深圳CSPM-3中级国标项目管理认证招生

CSPM-3中级项目管理专业人员认证&#xff0c;是中国标准化协会&#xff08;全国项目管理标准化技术委员会秘书处&#xff09;&#xff0c;面向社会开展项目管理专业人员能力的等级证书。旨在构建多层次从业人员培养培训体系&#xff0c;建立健全人才职业能力评价和激励机制的要…

基于时空RBF神经网络的混沌时间序列预测(Matlab代码实现)

&#x1f4a5;&#x1f4a5;&#x1f49e;&#x1f49e;欢迎来到本博客❤️❤️&#x1f4a5;&#x1f4a5; &#x1f3c6;博主优势&#xff1a;&#x1f31e;&#x1f31e;&#x1f31e;博客内容尽量做到思维缜密&#xff0c;逻辑清晰&#xff0c;为了方便读者。 ⛳️座右铭&a…

TCP的三次握手过程

TCP 是面向连接的协议&#xff0c;所以使用 TCP 前必须先建立连接&#xff0c;而建立连接是通过三次握手来进行的。三次握手的过程如下图&#xff1a; 刚开始客户端处于 closed 的状态&#xff0c;服务端处于 listen 状态。 第一次握手&#xff1a;客户端给服务端发一个 SYN 报…

python_day10_复写,类型注解

复写&#xff1a;重写父类属性 class Phone:IMEI Noneproducer "XM"def call_by_5g(self):print("5g网络")# 复写 class myPhone(Phone):producer "HUAWEI"def call_by_5g(self):print("复写")# 调用父类成员:方式1# print(f"…

Notepad++ 安装 compare 插件比较文本

1、打卡Notepad软件&#xff0c;找到插件选项&#xff0c;若是英文版的&#xff0c;则对应选择Plugins->Plugins admin&#xff1a; 2、搜索compare插件&#xff0c;点击安装&#xff1a; 3、此时会弹出一个下载插件页面&#xff1a; 4、很可惜&#xff0c;我网络原因&#…

[游戏开发][Unity] TPS射击游戏相机实现

技术难点&#xff1a;由于是第三人称射击游戏&#xff0c;角色和相机之间有夹角&#xff0c;所以枪口点和准星是有误差的&#xff0c;下面是和平精英手游截图&#xff0c;我用AK射击zhuzi using System.Collections; using System.Collections.Generic; using UnityEngine;publ…

MyBatis 系列2 -- 增加、删除、修改操作

1. 前言 上一系列介绍了MyBatis的背景,以及为什么我们使用MyBatis进行操作数据库,还实现了使用MyBatis进行查询数据库的,接下来我们继续将使用MyBatis操作数据库的其他三种基本操作进行总结. 目录 1. 前言 2. 增加用户操作 3. 修改用户操作 4. 删除用户操作 5. 多表查询操…

unity背景缓动动效

这算是一个很常见的小功能&#xff0c;比如我们在玩横版游戏的时候&#xff0c;背景动画会以一定的频率运动&#xff0c;其实现方式也有很多种。 比如&#xff0c;使用UGUI的imageanimtion动画的方式&#xff0c;自己k桢实现。 还可以使用材质球本身的功能来实现&#xff0c;关…

datatables.editor 2.2 for PHP/JS/NodeJS Crack

使用数据表编辑器在几分钟内创建自定义、完全可编辑的表 编辑器添加了三种编辑模式&#xff0c;以适应任何类型的应用程序 新增功能 编辑 删除 搜索&#xff1a; 名字位置办公室开始日期工资名字位置办公室开始日期工资佐藤爱里会计东京2008-11-28$162&#xff0c;700安吉莉卡拉…

linux服务器中安装java JDK1.8版本

我们远程连接自己的linux服务器 然后 我们先执行 sudo yum update更新一下软件包 然后 有个需要选择的地方 按y 然后 我们可以直接用 yum 来安装Java 1.8版本 执行 sudo yum install java-1.8.0-openjdk然后 问你是否选择按 y即可 搞完之后 我们检查一下 输入 java -vers…