Last active
September 9, 2023 22:44
-
-
Save trots/b8985b61242fcc3426883054c28e752d to your computer and use it in GitHub Desktop.
Working with QJSEngine in PySide6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from PySide6.QtCore import QCoreApplication, QObject, Slot | |
from PySide6.QtQml import QJSEngine | |
# Define class with invokable methods | |
class MyObject(QObject): | |
def __init__(self, parent = None): | |
super().__init__(parent) | |
@Slot() | |
def print_start(self): | |
print("Start") | |
@Slot(result=int) | |
def get_integer(self): | |
return 33 | |
@Slot(int) | |
def print_integer(self, value): | |
print("Integer is", value) | |
@Slot() | |
def print_finish(self): | |
print("Finish") | |
# Create application and JS engine | |
app = QCoreApplication() | |
engine = QJSEngine() | |
# Create MyObject instance and declare it in the JS engine | |
my_object = MyObject() | |
my_object_js = engine.newQObject(my_object) | |
# Define JS functions based on the MyObject methods | |
engine.globalObject().setProperty("printStart", my_object_js.property("print_start")) | |
engine.globalObject().setProperty("getInteger", my_object_js.property("get_integer")) | |
engine.globalObject().setProperty("printInteger", my_object_js.property("print_integer")) | |
engine.globalObject().setProperty("printFinish", my_object_js.property("print_finish")) | |
# Read JS script | |
script = open("test.js", "r").read() | |
# Run JS script | |
res = engine.evaluate(script) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
printStart(); | |
var i = getInteger(); | |
printInteger(i); | |
printFinish(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment