欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

QT和vue交互的實(shí)現(xiàn)示例

 更新時(shí)間:2023年07月20日 15:43:18   作者:南有嘉念  
本文主要介紹了QT和vue交互的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

1、首先在vue項(xiàng)目中引入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項(xiàng)目中用qrc引入

6、效果圖

注意:history只能用hash模式,不然里面的東西不能加載

到此這篇關(guān)于QT和vue交互的實(shí)現(xiàn)示例的文章就介紹到這了,更多相關(guān)QT vue交互內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • vue?如何配置eslint代碼檢查

    vue?如何配置eslint代碼檢查

    這篇文章主要介紹了vue?如何配置eslint代碼檢查,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-04-04
  • Vuejs第十二篇之動(dòng)態(tài)組件全面解析

    Vuejs第十二篇之動(dòng)態(tài)組件全面解析

    組件(Component)是 Vue.js 最強(qiáng)大的功能之一。組件可以擴(kuò)展 HTML 元素,封裝可重用的代碼。接下來通過本文給大家介紹Vuejs第十二篇之動(dòng)態(tài)組件,非常不錯(cuò),具有參考借鑒價(jià)值,感興趣的朋友一起看看吧
    2016-09-09
  • 詳解如何實(shí)現(xiàn)在Vue中導(dǎo)入Excel文件

    詳解如何實(shí)現(xiàn)在Vue中導(dǎo)入Excel文件

    這篇文章主要介紹了如何在Vue中導(dǎo)入Excel文件,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)或工作有一定幫助,感興趣的小伙伴可以跟隨小編一起了解一下
    2022-01-01
  • vue3 vite如何讀取文件內(nèi)容

    vue3 vite如何讀取文件內(nèi)容

    這篇文章主要介紹了vue3 vite如何讀取文件內(nèi)容問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-05-05
  • vue前端HbuliderEslint實(shí)時(shí)校驗(yàn)自動(dòng)修復(fù)設(shè)置

    vue前端HbuliderEslint實(shí)時(shí)校驗(yàn)自動(dòng)修復(fù)設(shè)置

    這篇文章主要為大家介紹了vue前端中Hbulider中Eslint實(shí)時(shí)校驗(yàn)自動(dòng)修復(fù)設(shè)置操作過程,有需要的朋友可以借鑒參考下希望能夠有所幫助
    2021-10-10
  • Vue3?源碼解讀之?Teleport?組件使用示例

    Vue3?源碼解讀之?Teleport?組件使用示例

    這篇文章主要為大家介紹了Vue3?源碼解讀之?Teleport?組件使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-08-08
  • 基于前端VUE+ElementUI實(shí)現(xiàn)table行上移或下移功能(支持跨頁移動(dòng))

    基于前端VUE+ElementUI實(shí)現(xiàn)table行上移或下移功能(支持跨頁移動(dòng))

    有時(shí)候需要前端實(shí)現(xiàn)上移和下移功能,下面這篇文章主要給大家介紹了關(guān)于如何基于前端VUE+ElementUI實(shí)現(xiàn)table行上移或下移(支持跨頁移動(dòng))的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-07-07
  • vue3.2中的vuex使用詳解

    vue3.2中的vuex使用詳解

    這篇文章主要介紹了vue3.2中的vuex使用詳解,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-04-04
  • vue使用video插件vue-video-player的示例

    vue使用video插件vue-video-player的示例

    這篇文章主要介紹了vue使用video插件vue-video-player的示例,幫助大家更好的理解和使用vue插件,感興趣的朋友可以了解下
    2020-10-10
  • VUE+Canvas實(shí)現(xiàn)財(cái)神爺接元寶小游戲

    VUE+Canvas實(shí)現(xiàn)財(cái)神爺接元寶小游戲

    這篇文章主要介紹了VUE+Canvas實(shí)現(xiàn)財(cái)神爺接元寶小游戲,需要的朋友可以參考下本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2021-04-04

最新評論