Skip to content

Instantly share code, notes, and snippets.

@qpxu007
Forked from mphuie/index.html
Created January 21, 2021 01:49
Show Gist options
  • Save qpxu007/0feb88772a252169d7721e00c8073828 to your computer and use it in GitHub Desktop.
Save qpxu007/0feb88772a252169d7721e00c8073828 to your computer and use it in GitHub Desktop.
pyqt webview javascript -> python example
<html>
<head>
<script src="qrc:///qtwebchannel/qwebchannel.js"></script>
<style>
::selection {
background:transparent;
}
</style>
</head>
<body>
<div class="container">
<h1>Hi!</h1>
</div>
<script language="JavaScript">
new QWebChannel(qt.webChannelTransport, function (channel) {
window.handler = channel.objects.handler;
handler.test(function(retVal) {
// console.error as console.log message don't show up in the python console
console.error(JSON.stringify(retVal));
})
});
</script>
</body>
</html>
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWebChannel import QWebChannel
from PyQt5.QtCore import QObject, pyqtSlot, QUrl, QVariant
import os
class CallHandler(QObject):
@pyqtSlot(result=QVariant)
def test(self):
print('call received')
return QVariant({"abc": "def", "ab": 22})
# take an argument from javascript - JS: handler.test1('hello!')
@pyqtSlot(QVariant, result=QVariant)
def test1(self, args):
print('i got')
print(args)
return "ok"
class WebView(QWebEngineView):
def __init__(self):
super(WebView, self).__init__()
self.channel = QWebChannel()
self.handler = CallHandler()
self.channel.registerObject('handler', self.handler)
self.page().setWebChannel(self.channel)
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "index.html"))
local_url = QUrl.fromLocalFile(file_path)
self.load(local_url)
if __name__ == "__main__":
app = QApplication([])
view = WebView()
view.show()
app.exec_()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment