Difficulties accessing object in JavaScript using QWebChannel in other scope
I'm new to QWebChannel, so I apologize in advance if this is a stupid question. But I am having some difficulty figuring out how to access Qt objects/methods, elsewhere in my JavaScript app, using QWebChannel. The comments in the JS snippet below should clarify what I mean. I can access everything fine in the callback when I instantiate QWebChannel, but it seems like channel.objects loses its context outside of that...even if I try to make it global.
JS snippet:
Code:
new QWebChannel(qt.webChannelTransport, function (channel) {
channel.objects.bridge.sendMessage("hello"); // this works
window.bridge = channel.objects.bridge; // try to make global
});
function foo (msg) {
bridge.sendMessage("hello from foo"); // this doesn't work
window.bridge.sendMessage("hello from foo"); // this doesn't work
// how might I access sendMessage here?
}
On the Python side:
Code:
from PyQt5.QtWebEngineWidgets import QWebEnginePage
from PyQt5.QtCore import pyqtSlot, pyqtSignal
class MyWebPage(QWebEnginePage):
Bridge = pyqtSignal(list)
def __init__(self):
super(MyWebPage, self).__init__()
def javaScriptConsoleMessage(self, level, message, lineNumber, sourceId):
toWrite = "JsConsole(%s:%d):\n %s" % (sourceId, lineNumber, message)
self._log.info(toWrite)
print toWrite
@pyqtSlot(str)
def sendMessage(self, msg):
print msg
self.Bridge.emit(msg) # over here, a signal is emitted with the message for elsewhere in the code
Any help would be greatly appreciated. I am using the qtwebchannel.js file included in Qt5.6 and just loading it into my HTML document.
Re: Difficulties accessing object in JavaScript using QWebChannel in other scope
Maybe the JS object created by new QWebChannel(...) needs to be saved somewhere as well?
E.g. maybe it is currently garbage collected by the JS engine after the callback ran.
Cheers,
_
Re: Difficulties accessing object in JavaScript using QWebChannel in other scope
Thank you for the reply!
Quote:
Maybe the JS object created by new QWebChannel(...) needs to be saved somewhere as well?
E.g. maybe it is currently garbage collected by the JS engine after the callback ran.
Do you mean doing something like:
Code:
window.webChannel = new QWebChannel(qt.webChannelTransport, function (channel) {
channel.objects.bridge.sendMessage("hello"); // this works
window.bridge = channel.objects.bridge; // try to make global
});
Unfortunately, that doesn't seem to fix the problem either. :confused:
Re: Difficulties accessing object in JavaScript using QWebChannel in other scope
Hmm, yes, that's what I had in mind.
All examples seem to indicate that this and your original approach should work.
Does the object still exist on the application side?
Cheers,
_