1
我想,以顯示與QWebView
的單張地圖(從here啓發)。我的文件夾的結構如下所示:PyQt5 QWebView:加載HTML文件加載.js文件
webkit_leaflet/
├── map.html
├── map.js
└── map.py
當我從map.html
,其中包括map.js
所有內容運行map.py
,然後代碼工作。
from PyQt5 import QtWidgets, QtWebKitWidgets
import sys
# Create application
app = QtWidgets.QApplication(sys.argv)
# Add window
win = QtWidgets.QWidget()
win.setWindowTitle('QWebView Map Test')
# Add layout
layout = QtWidgets.QVBoxLayout()
win.setLayout(layout)
# Create QWebView
view = QtWebKitWidgets.QWebView()
# include code from map.html and map.js
view.setHtml('''
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<style>
body { padding: 0; margin: 0; }
html, body, #map { height: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script>
var map = L.map('map').setView([42.35, -71.08], 13);
L.tileLayer('http://tiles.mapc.org/basemap/{z}/{x}/{y}.png',
{
maxZoom: 18,
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
'<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="http://mapbox.com">Mapbox</a>',
id: 'examples.map-i86nkdio',
}).addTo(map);
</script>
</body>
</html>
''')
# Add QWebView to the layout
layout.addWidget(view)
# Show window, run app
win.show()
app.exec_()
但是,如果我嘗試加載map.html
與QtCore.QUrl()
沒有任何反應。
from PyQt5 import QtCore, QtWidgets, QtWebKitWidgets
import sys
# Create application
app = QtWidgets.QApplication(sys.argv)
# Add window
win = QtWidgets.QWidget()
win.setWindowTitle('QWebView Map Test')
# Add layout
layout = QtWidgets.QVBoxLayout()
win.setLayout(layout)
# Create QWebView
view = QtWebKitWidgets.QWebView()
# load .html file
view.load(QtCore.QUrl('map.html'))
layout.addWidget(view)
win.show()
app.exec_()
有誰請告訴我如何顯示PyQt5 .html文件的內容時,我從外部.html文件中加載JavaScript文件?
這裏是map.html
代碼:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<style>
body { padding: 0; margin: 0; }
html, body, #map { height: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script src="map.js"></script>
</body>
</html>
,也爲map.js
var map = L.map('map').setView([42.35, -71.08], 13);
L.tileLayer('http://tiles.mapc.org/basemap/{z}/{x}/{y}.png',
{
maxZoom: 18,
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
'<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="http://mapbox.com">Mapbox</a>',
id: 'examples.map-i86nkdio',
}).addTo(map);
這是否對你的工作?我試過了,但它仍然不起作用。 – dliv
是的,它的作品,但我只是意識到我正在使用'map.html'的絕對路徑。只用'map.html'就會失敗。我會更新我的回答 – user3419537
完美,非常感謝你,現在它的工作。 :) – dliv