Files
tk-mini-program-PC/src/utils/pythonBridge.js

44 lines
960 B
JavaScript
Raw Normal View History

2025-04-03 16:41:54 +08:00
// pythonBridge.js
import { ref, onMounted } from 'vue';
export function usePythonBridge() {
const bridge = ref(null);
// 初始化 QWebChannel
const initBridge = () => {
new QWebChannel(qt.webChannelTransport, (channel) => {
bridge.value = channel.objects.bridge;
});
};
// 调用 Python 方法
2025-04-07 18:26:39 +08:00
const fetchDataConfig = (data) => {
return new Promise((resolve, reject) => {
if (!bridge.value) {
reject(new Error('返回出错,请检查是否已连接到 Python'));
return;
}
bridge.value.fetchDataConfig(data, function (result) {
resolve(result);
});
});
2025-04-03 16:41:54 +08:00
};
// 从 Python 获取数据
2025-04-07 18:26:39 +08:00
const getPythonData = (data) => {
2025-04-03 16:41:54 +08:00
if (bridge.value) {
2025-04-07 18:26:39 +08:00
bridge.value.stringToJs(data, function (result) {
alert(result);
});
2025-04-03 16:41:54 +08:00
}
};
// 在组件挂载时初始化桥接
onMounted(initBridge);
return {
2025-04-07 18:26:39 +08:00
fetchDataConfig,
2025-04-03 16:41:54 +08:00
getPythonData
};
}