Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call javascript function from PyQT

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)"))

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>

How can I call addMarker from Python?

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.

I also tried calling evaluateJavaScript("addMarker(-33.89,151.275)") on the frame.documentElement() object and that didn't work either.

like image 971
Dan Avatar asked May 04 '11 14:05

Dan


2 Answers

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.

like image 125
Dan Avatar answered Oct 17 '22 15:10

Dan


http://pysnippet.blogspot.com/2010/01/more-fun-with-qwebkit.html might help.

The only difference I can see between the two things you tried is that alert() is part of the standard functions. Maybe you need a document.addmarker() instead of just addmarker() ?

like image 2
Tom Macdonald Avatar answered Oct 17 '22 16:10

Tom Macdonald