如何从PyQT调用JavaScript函数 [英] How to call javascript function from PyQT
问题描述
我正在尝试使用python与Google地图进行互动。我使用QWebView在PyQT中构建了一个应用程序。所述QWebView加载一个本地HTML页面,如下所示:
I'm trying to interact with a google map using python. I've built an application in PyQT with a QWebView. The QWebView loads a local html page as shown here:
browser = QwebView()
browser.load(QUrl("file:///c:/main.html"))
frame = browser.page().currentFrame()
frame.evaluateJavaScript(QString("addMarker(-33.89, 151.275)"))
html页面如下:
The html page is as follows:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var map;
function initialize() {
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
}
function addMarker(lat, lng) {
var myLatLng = new google.maps.LatLng(lat, lng);
var beachMarker = new google.maps.Marker({position: myLatLng,
map: map
});
}
</script>
</head>
<body onload="initialize();">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
如何从Python中调用 addMarker
?
How can I call addMarker
from Python?
我试着从HTML调用addMarker(将调用添加到 onload
调用中),然后尝试使用来自python的简单javascript表达式( frame.evaluateJavaScript(alert(5))
)。这两个工作,所以我知道 addMarker
和 evaluateJavaScript
可以工作,我只是不知道如何。
I have tried calling addMarker from the HTML (added the call to the onload
call) and I tried using a simple javascript expression from the python (frame.evaluateJavaScript("alert(5)")
). Both of those worked, so I know that addMarker
and evaluateJavaScript
can work, I just don't know how.
我还试图调用 evaluateJavaScript( addMarker(-33.89,151.275))
上的 frame.documentElement()
对象和也不能工作。
I also tried calling evaluateJavaScript("addMarker(-33.89,151.275)")
on the frame.documentElement()
object and that didn't work either.
推荐答案
在错误是我需要等待页面加载。我添加了一个连接到 evaluateJavaScript(addMarker(-33.89,151.275))
调用的按钮。当我点击按钮(加载页面后)时,标记按预期添加。
The error was that I needed to wait for the page to load. I added a button that was connected to the evaluateJavaScript("addMarker(-33.89,151.275)")
call. When I clicked the button (after the page loaded), the marker was added as expected.
这篇关于如何从PyQT调用JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!