如何通过 C++ 触发 JavaScript 事件在QWebView中
请注意,我是 Qt 开发的完全初学者。
我有一个 QWebView,其中添加了一个 QObject 到 JavaScript 窗口对象。 如何在该对象上触发 JS 事件?
view->page()->mainFrame()->addToJavaScriptWindowObject(objName,obj);
我希望能够使用 addEventListener 监听事件。
window.objName.addEventListener('customEventName',function(e){ ... });
感谢您的任何帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能那样做。只有 DOM 树中的节点才能触发事件,并且您注入的对象不是节点。我建议你考虑使用信号槽机制。您可以将 JS 中的槽连接到将在 C++ 代码中发出的信号:
槽只是一个 JS 函数,您将在代码的 JS 部分中声明它:
它需要与中声明的参数一样多的参数信号的签名。
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:
slot is just an JS function, that you'll declare in the JS part of your code:
It takes as many arguments as are declared in the signal's signature.
在最近的一个项目中,我使用了以下技术:
此方法查找所有
这当然是与 Qt 插件 Widgets 一起使用的。我没有使用纯 HTML 对其进行测试(即不使用 Qt 插件的情况)。
In a recent project I used the following technique:
This method looks up all
<object>
tags and connects theplaying
signal to the Javascript functionplayingSlot()
.The
playingSlot()
function in its turn creates anEvent
object with the nameplay
and dispatches it as an ordinary DOM event.The HTML file then looks like:
This is of course working with Qt plugin Widgets. I did not test it with plain HTML (i.e. where no Qt plugins are used).