EDIT:
I've found a solution here: how do I correctly return values from pyqt to JavaScript?
I'll post the code first:
Python code:
class JSBridge(QObject):
def __init__(self, parent=None):
super(JSBridge, self).__init__(parent)
@pyqtSlot(bool)
def fromJStoPython(self, param):
print param
print param.toBool()
@pyqtSlot()
def returnValue()
return "hello world"
class another():
...
view = QWebView()
frame = view.page().mainFrame()
param = "blabla"
frame.evaluateJavaScript("printIt('" + param + "');")
paramBool = True
frame.evaluateJavaScript("fromPythonWithParameterBool('" + paramBool + "');")
JavaScript:
function printIt(param)
{
alert(param);
}
function toPython()
{
jsBridgeInst.fromJStoPython(true);
}
// now here functions I've questions about:
function fromPythonWithParameterBool(param)
{
alert(param);
}
function fromPythonReturnValue()
{
res = jsBridgeInst.returnValue();
alert(res);
}
Now to my question:
The printIt
function works fine. So the param is interpreted as a String.
The fromJStoPython
function also works fine. The print statement shows it's a QVariant
.
But the fromPythonWithParameterBool
function does not work, because I have to convert paramBool
into a string in order to connect it. If I do so, it's printing the string value (but I want it to be boolean). Is it possible to pass a boolean, so that in JavaScript I can work with it as a boolean? If yes, how do you do it?
And for the fromPythonReturnValue
function, it does not show an error, but res
is undefined. Why?
I was searching for that problem, but mostly the examples/tutorials show standard stuff like:
evaluateJavaScript("alert('9')";)
I've worked with Java and SWT, and there I could just simply return a value (as in the formPythonReturnValue
method). There was a Browser class where you could implement your methods to call, just like JSBridge.
The
fromPythonWithParameterBool
doesn't work because you are not generating an input string that can be evaluated as javascript.What you need to do is something like this:
So the resulting string is now a fragment of valid javascript.
The problem with
fromPythonReturnValue
(as you already seem to have discovered), is that you are not specifying the type of the return value. This has to be done explicitly, using the pyqtSlot decorator: