Skip to content

Instantly share code, notes, and snippets.

@POMXARK
Created June 2, 2024 17:54
Show Gist options
  • Save POMXARK/ce91e20503e2fbbd3b3e9c2582768ee0 to your computer and use it in GitHub Desktop.
Save POMXARK/ce91e20503e2fbbd3b3e9c2582768ee0 to your computer and use it in GitHub Desktop.
pyqt webview javascript -> python example qtwebchannel PySide6 QWebChannel inject script
import json
from PySide6 import QtCore, QtWebChannel
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.test1('hello!')
@Slot(QJsonValue)
def send_to_server(self, *args):
print('send_to_server ->')
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__), "test.html"))
local_url = QUrl.fromLocalFile(file_path)
self.load(local_url)
self.loadFinished.connect(self.onLoadFinished)
def onLoadFinished(self, ok):
if ok:
self.load_qwebchannel()
script_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "test.js"))
self.page().runJavaScript(open(script_path, 'r').read())
def load_qwebchannel(self):
file = QtCore.QFile(":/qtwebchannel/qwebchannel.js")
if file.open(QtCore.QIODevice.ReadOnly):
content = file.readAll()
file.close()
self.page().runJavaScript(content.data().decode())
if self.page().webChannel() is None:
channel = QtWebChannel.QWebChannel(self)
self.page().setWebChannel(channel)
if __name__ == "__main__":
app = QApplication([])
view = WebView()
view.show()
app.exec_()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>Test</p>
<ul id="test">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
</body>
</html>
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')
});
const element = document.getElementsByTagName("p");
element[0].style.border = "thick solid #0000FF"
const test = document.getElementById("test");
// This handler will be executed only once when the cursor
// moves over the unordered list
test.addEventListener(
"mouseenter",
(event) => {
// highlight the mouseenter target
event.target.style.color = "purple";
},
false,
);
// This handler will be executed every time the cursor
// is moved over a different list item
test.addEventListener(
"mouseover",
(event) => {
// highlight the mouseover target
event.target.style.color = "orange";
},
false,
);
test.addEventListener(
"mouseout",
(event) => {
// reset the color after a short delay
setTimeout(() => {
event.target.style.color = "";
}, 500);
},
false,
);
test.addEventListener("click", (event) => {
alert(event.target.innerHTML)
handler.send_to_server(event.target.innerHTML)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment