将启用地理位置定位功能从pyQt5.xx转换为pyQt4.xxx?

时间:2018-07-15 13:07:23

标签: python python-2.7 pyqt geolocation pyqt4

我从这里找到了这段代码:https://gist.github.com/eyllanesc/12d82588c3d56bb00ecf5d3d300c92ef

from PyQt5.QtCore import QUrl, QDir
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEnginePage
from PyQt5.QtWidgets import QApplication


class OpenLayersView(QWebEngineView):
    def __init__(self, parent=None):
        QWebEngineView.__init__(self, parent)
        self.page().setUrl(QUrl.fromLocalFile(QDir.current().filePath("index.html")))
        self.page().featurePermissionRequested.connect(self.onFeaturePermissionRequested)

    def onFeaturePermissionRequested(self, securityOrigin, feature):
        print(securityOrigin, feature)

        self.page().setFeaturePermission(securityOrigin,
                                         QWebEnginePage.Geolocation,
                                         QWebEnginePage.PermissionGrantedByUser)

if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    w = OpenLayersView()
    w.show()
    sys.exit(app.exec_())

我想创建一个自定义的pyQt 4.xx浏览器,并且尝试使用此代码中的函数,但它根本无法工作。我没有看到任何错误,但是这里没有显示启用的Geolocation API:https://detectmybrowser.com/(在HTML 5 Advanced features接口上)。 我需要这样做是因为我想访问一个首先使用此地理位置的网站。 现在,我想运行一个可检测到我的位置的javascript,但这也不起作用。 这是我要运行的脚本:

js_location = """
var handleGeolocation = function() {

      var coordinates;
      var geolocation = new ol.Geolocation({
        projection: view.getProjection(),
        tracking: true
      });
      // handle geolocation error.
      geolocation.on('error', function (error) {
        var info = document.getElementById('info');
        info.innerHTML = error.message;
        info.style.display = '';
      });

      var accuracyFeature = new ol.Feature();
      geolocation.on('change:accuracyGeometry', function () {
        accuracyFeature.setGeometry(geolocation.getAccuracyGeometry());
      });

      var positionFeature = new ol.Feature();
      positionFeature.setStyle(new ol.style.Style({
        image: new ol.style.Circle({
          radius: 6,
          fill: new ol.style.Fill({
            color: '#3399CC'
          }),
          stroke: new ol.style.Stroke({
            color: '#fff',
            width: 2
          })
        })
      }));

      geolocation.once('change:position', function () {
        coordinates = geolocation.getPosition();
        positionFeature.setGeometry(coordinates ?
          new ol.geom.Point(coordinates) : null);
        map.getView().setCenter(coordinates);
        map.getView().setZoom(17);
      });

      new ol.layer.Vector({
        map: map,
        source: new ol.source.Vector({
          features: [accuracyFeature, positionFeature]
        })
      });
    }
"""

因此,我试图在PyQT 4.xx浏览器中像这样调用和评估此位置javascript:

class Browser(QWebView):
    def __init__(self, gui=False, user_agent=None, load_images=True, load_javascript=True, load_java=True,
                 load_plugins=True, timeout=20, delay=5, app=None):
        """Widget class that contains the address bar, webview for rendering webpages, and a table for displaying results

        user_agent: the user-agent when downloading content
        proxy: a QNetworkProxy to download through
        load_images: whether to download images
        load_javascript: whether to enable javascript
        load_java: whether to enable java
        load_plugins: whether to enable browser plugins
        timeout: the maximum amount of seconds to wait for a request
        delay: the minimum amount of seconds to wait between requests
        app: QApplication object so that can instantiate multiple browser objects
        use_cache: whether to cache all replies
        """
        # must instantiate the QApplication object before any other Qt objects
        self.app = app or QApplication(sys.argv)
        super(Browser, self).__init__()

        page = WebPage(user_agent)
        manager = NetworkAccessManager()
        page.setNetworkAccessManager(manager)
        self.setPage(page)
        page.networkAccessManager().finished.connect(self.finished)
        # set whether to enable plugins, images, and java
        self.settings().setAttribute(QWebSettings.AutoLoadImages, load_images)
        self.settings().setAttribute(QWebSettings.JavascriptEnabled, load_javascript)
        self.settings().setAttribute(QWebSettings.JavaEnabled, load_java)
        self.settings().setAttribute(QWebSettings.PluginsEnabled, load_plugins)
        self.settings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
        self.settings().setAttribute(QWebSettings.AcceleratedCompositingEnabled, True)
        self.settings().setAttribute(QWebSettings.DnsPrefetchEnabled, True)
        self.settings().setAttribute(QWebSettings.WebGLEnabled, True)
        self.settings().setAttribute(QWebSettings.HyperlinkAuditingEnabled, True)
        self.settings().setAttribute(QWebSettings.LocalStorageDatabaseEnabled, True)
        self.settings().setAttribute(QWebSettings.LocalStorageEnabled, True)
        # prepare to run javascript functions to get my location in the custom browser: <==============================!!!
        self.page().mainFrame().addToJavaScriptWindowObject("handleGeolocation", self)
        self.loadFinished.connect(self.on_loadFinished)
        self.timeout = timeout
        self.delay = delay

        @QtCore.pyqtSlot()
    def on_loadFinished(self):
        self.page().mainFrame().evaluateJavaScript(js_location)

但是遗憾的是,它仍然根本无法工作。 有什么帮助吗? 自两三天以来,我一直试图解决此问题,但没有成功...

非常感谢您!

0 个答案:

没有答案