How do I add a js map to Pyqt5?

Viewed 40

I want to add the map provided by Marinetraffic to pyqt5. When I add the HTML codes provided by MarineTraffic to my own program, it doesn't work. The map I want to add: MarineTraffic Map JS

from PyQt5 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets, QtWebChannel


class Backend(QtCore.QObject):
    valueChanged = QtCore.pyqtSignal(str)

    def __init__(self, parent=None):
        super().__init__(parent)
        self._value = ""

    @QtCore.pyqtProperty(str)
    def value(self):
        return self._value

    @value.setter
    def value(self, v):
        self._value = v
        self.valueChanged.emit(v)


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.webEngineView = QtWebEngineWidgets.QWebEngineView()
        self.label = QtWidgets.QLabel(alignment=QtCore.Qt.AlignCenter)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(self.webEngineView, stretch=1)
        lay.addWidget(self.label, stretch=1)

        backend = Backend(self)
        backend.valueChanged.connect(self.label.setText)
        backend.valueChanged.connect(self.foo_function)
        self.channel = QtWebChannel.QWebChannel()
        self.channel.registerObject("backend", backend)
        self.webEngineView.page().setWebChannel(self.channel)

        path = "index.html"
        self.webEngineView.setUrl(QtCore.QUrl.fromLocalFile(path))

    @QtCore.pyqtSlot(str)
    def foo_function(self, value):
        print(value)


if __name__ == "__main__":
    import sys

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

When I run it, I get a connection failed error. As a result of my searches, I get the same error in all the methods I tried, where am I doing wrong, can you help?

1 Answers

Read the documentation for QtCore.QUrl.fromLocalFile :

QtCore.QUrl.fromLocalFile

"A file URL with a relative path only makes sense if there is a base URL to resolve it against."

So we add the base path:

import os
...

        path = os.getcwd() + "\\index.html"
        self.webEngineView.setUrl(QtCore.QUrl.fromLocalFile(path))


Added path compatibility between os (edited)

from pathlib import Path
...
        base_path = Path(Path.cwd())
        full_path = base_path.joinpath('index.html')
        self.webEngineView.setUrl(QtCore.QUrl.fromLocalFile(str(full_path)))

Related