Skip to content

Instantly share code, notes, and snippets.

@POMXARK
Forked from mphuie/index.html
Last active June 2, 2024 16:01
Show Gist options
  • Save POMXARK/c9603fa9d1720ed00f6d4c5b866b4e57 to your computer and use it in GitHub Desktop.
Save POMXARK/c9603fa9d1720ed00f6d4c5b866b4e57 to your computer and use it in GitHub Desktop.
pyqt webview javascript -> python example qtwebchannel PySide6 QWebChannel QWebEngineView
<html>
<head>
<script src="qrc:///qtwebchannel/qwebchannel.js"></script>
<style>
::selection {
background: transparent;
}
</style>
</head>
<body>
<div class="container">
<h1>Hi!</h1>
</div>
<script>
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));
})
handler.send_to_server('hello')
});
</script>
</body>
</html>
import json
from PySide6.QtWidgets import QApplication
from PySide6.QtWebEngineWidgets import QWebEngineView
from PySide6.QtWebChannel import QWebChannel
from PySide6.QtCore import QObject, Slot, QUrl, QJsonValue
import os
class CallHandler(QObject):
@Slot(result=str)
def test(self):
print('call received')
return json.dumps({"abc": "def", "ab": 22})
# take an argument from javascript - JS: handler.send_to_server('hello!')
@Slot(QJsonValue)
def send_to_server(self, *args):
print('i got')
print(args)
for arg in args:
print(arg.toString())
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