我正试图展示QWebView
的传单地图(灵感来自这里)。我的文件夹的结构如下所示:
webkit_leaflet/
├── map.html
├── map.js
└── map.py
当我运行map.py
时,包含map.html
和map.js
的所有内容,然后代码工作。
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_()
但是,如果我尝试用QtCore.QUrl()
加载map.html
,什么都不会发生。
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);
使用QUrl.fromLocalFile传递html文件。似乎还需要传递文件的绝对路径。
import os
view.load(QtCore.QUrl.fromLocalFile(os.path.abspath('map.html')))