gpt4 book ai didi

javascript - 如何在 QML 上使用 JavaScript 库

转载 作者:行者123 更新时间:2023-11-30 11:06:08 24 4
gpt4 key购买 nike

我在 5.12.2 上使用一些带有 QML 的 javascript 库。其中一些像 Proj4JS 一样工作。但是在使用 geographiclib.js 时出现错误带有 QML 的库。如何将 JavaScript 库导入 QML?

主.qml:

import QtQuick 2.12
import QtQuick.Window 2.12
import "geographiclib.js" as MyGeo
Window {
visible: true
width: 640
height: 480
Component.onCompleted: {
var Geodesic = MyGeo.GeographicLib.Geodesic,
DMS = MyGeo.GeographicLib.DMS,
geod = Geodesic.WGS84;
var r = geod.Inverse(23, 22, 44, 29);
console.log("distance is: ", r.s12.toFixed(3) + " m")
}
}

错误:

qrc:/geographiclib.js:3081: ReferenceError: window is not defined
qrc:/main.qml:9: TypeError: Cannot read property 'Geodesic' of undefined

最佳答案

最简单的方法是让 GeographicLib 全局可用:

geographiclib.js 文件的末尾,更改

window.GeographicLib = geo;

this.GeographicLib = geo;

然后你就可以使用:

main.qml:

import QtQuick 2.12
import QtQuick.Window 2.12
import "geographiclib.js" as ThenItWillBeAvailableGlobally
Window {
visible: true
width: 640
height: 480
Component.onCompleted: {
var Geodesic = GeographicLib.Geodesic,
DMS = GeographicLib.DMS,
geod = Geodesic.WGS84;
var r = geod.Inverse(23, 22, 44, 29);
console.log("distance is: ", JSON.stringify(r))
}
}

导致:

qml: distance is:  {"lat1":23,"lat2":44,"lon1":22,"lon2":29,"a12":21.754466225665134,"s12":2416081.7576307985,"azi1":13.736139413215236,"azi2":17.669059640534535}

如果您根本不想更改 geographiclib.js 文件,您可以添加一个全局窗口对象,例如:

window.js:

this.window = this;

然后使用:

import QtQuick 2.12
import QtQuick.Window 2.12
import "window.js" as ThenWindowWillBeAvailableGlobally
import "geographiclib.js" as ThenGeographicLibWillBeAvailableGlobally
Window {
visible: true
width: 640
height: 480
Component.onCompleted: {
var Geodesic = GeographicLib.Geodesic,
DMS = GeographicLib.DMS,
geod = Geodesic.WGS84;
var r = geod.Inverse(23, 22, 44, 29);
console.log("distance is: ", JSON.stringify(r))
}
}

如果您不想添加任何全局变量,但很乐意编辑 geographiclib.js 文件,那么您可以将第 68 行移动到文件顶部:

var GeographicLib = {};
/*
* Geodesic routines from GeographicLib translated to JavaScript. See
* https://geographiclib.sourceforge.io/html/js/

并在文件更改的末尾

  } else {
/******** otherwise just pollute our global namespace ********/
window.GeographicLib = geo;
}
});

  } else if (typeof window === 'object') {
/******** otherwise just pollute our global namespace ********/
window.GeographicLib = geo;
}
});

然后您的 main.qml 将正常工作。

关于javascript - 如何在 QML 上使用 JavaScript 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55531885/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com