Based on QT QWebEnginePage::setWebChannel() transport object and Qt: Cannot invoke shared object methods/properties from javascript I tried to make a small demo to test the
I had the same issue recently. After some investigation, I figured out how to make it work. Big thanks to the answer of this question: How to use Qt WebEngine and QWebChannel?
In order to get the return value of a method of your QObject, you need to define a Q_PROPERTY wrapping your QObject method. For example:
class SharedObject : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE int getIntValue();
Q_PROPERTY(int intValue READ getIntValue)
Q_INVOKABLE QString getStringValue();
Q_PROPERTY(QString stringValue READ getStringValue)
}
And then in your HTML, do this:
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function () {
new QWebChannel(qt.webChannelTransport, function (channel) {
window.sharedObject = channel.objects.sharedObject;
alert("intValue: " + sharedObject.intValue);
alert("stringValue: " + sharedObject.stringValue);
});
});
</script>
You should be able to see intValue and stringValue in your JavaScript code. The important bit is to use Q_PROPERTY I think.
Anyway, this resolves my problem, and I hope it helps for someone else too.
Faced same issue... Reading doc's carefully gave me the answer. The answer is that communication between Qt and JS in Qt5 is asynchronous. You have to provide callback function which will be called after method completed and result value received.
Instead of calling
var n = theQtObj.getInt(X);
PrintLog(" back in js with n="+n);
you can call at as
theQtObj.getInt(X, function(n) {
PrintLog(" back in js with n="+n);
});