Search code examples
javascriptc++eventsqtqwebview

How to fire a JavaScript event via C++ in QWebView


please note that I'm a complete beginner to Qt development.

I have a QWebView with a QObject added to the JavaScript window object. How do I fire a JS event on that object?

view->page()->mainFrame()->addToJavaScriptWindowObject(objName,obj);

I want to be able to listen to events using addEventListener.

window.objName.addEventListener('customEventName',function(e){ ... });

Thanks for any help.


Solution

  • You cannot do that. Only nodes in a DOM tree can fire events and the object you're injecting is not a node. I suggest you consider using the signal-slot mechanism instead. You can connect a slot in JS to a signal that you'll be emitting in your C++ code:

    window.objectName.signalName.connect(slot);
    

    slot is just an JS function, that you'll declare in the JS part of your code:

    function slot(arg1, arg2, ...)
    {
    }
    

    It takes as many arguments as are declared in the signal's signature.