PDA

View Full Version : Difficulties accessing object in JavaScript using QWebChannel in other scope



tabularasa
17th May 2016, 06:33
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:


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:


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.

anda_skoa
17th May 2016, 06:59
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,
_

tabularasa
17th May 2016, 23:17
Thank you for the reply!


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:


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:

anda_skoa
18th May 2016, 06:47
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,
_