如何在 QWebView/QWebPage 中获取焦点元素?
我需要能够对 QWebPage 中的焦点变化做出反应。我使用了 microFocusChanged() 信号,它给了我几乎理想的行为,但无论如何我不知道如何知道选择了哪个元素。当页面上的任何可编辑元素获得或失去焦点时,我想执行一些操作。
先感谢您
i need to be able to react on focus changes in QWebPage. I used microFocusChanged() signal and it gives me almost desirable behavior, but anyway i don't know how to know which element is selected. I want to do some actions when any editable element on page gets or loses focus.
Thank you in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要处理页面中的任何 HTML 事件,请执行以下操作:
添加焦点更改处理程序的 JavaScript 应遍历所有文本元素并添加 onfocus 和 onblur 处理程序。更好的方法是向 documentElement 添加单个处理程序并使用事件冒泡。不幸的是,onblur 广告 onfocus 不会冒泡。幸运的是,它们有一个名为 DOMFocusIn 和 DOMFocusOut 的冒泡对应项。
这是捕获页面文本元素的焦点输入/输出事件的完整示例。它在主窗口上声明了两个槽
handleFocusIn
和handleFocusOut
,以便从 JavaScript 调用,并将主窗口注册为名为MainWindow
的全局 JavaScript 变量。然后运行 JavaScript 将 DOMFocusIn/DOMFocusOut 事件绑定到这些槽(间接地,因为我们需要过滤掉非文本元素)。(如果你真的看不懂Python,我可以用C++重写)。
To handle any HTML event within a page you do the following:
JavaScript to add focus change handlers should traverse all text elements and add onfocus and onblur handlers. Better yet is to add single handler to documentElement and use event bubbling. Unfortunately, onblur ad onfocus do not bubble. Fortunately, they have a bubbling counterparts called DOMFocusIn and DOMFocusOut.
Here's a complete examlpe of catching focus in/out events for page text elements. It declares two slots
handleFocusIn
andhandleFocusOut
on the main window to be called from JavaScripts and registers main window as a global JavaScript variable namedMainWindow
. In then runs JavaScript to bind DOMFocusIn/DOMFocusOut events to these slots (indirectly, because we need to filter out non-text elemnts).(I may rewrite in in C++ if you REALLY can't figure out Python).
我遇到了同样的问题,但不想使用 Javascript ,因为我希望它即使在
QWebSettings
中禁用 javascript 的情况下也能工作。我基本上可以想到两种方法:按照建议监听
microFocusChanged
信号,然后执行以下操作:这当然会产生一些开销,因为
microFocusChanged
会被多次发出,而且在许多情况下,不仅仅是在选择输入字段时(例如,在选择文本时)。在
loadFinished
中执行此操作可能也有意义,因为元素可以自动聚焦。我还没有测试过这个,但打算很快实现它。
如果我们只关心鼠标点击,则扩展
mousePressEvent
并在那里执行hitTestContent
:I had the same problem but didn't want to use Javascript , as I wanted it to work even with javascript disabled in
QWebSettings
. I basically can think of two approaches:Listening to the
microFocusChanged
signal as suggested, and then doing something like:This of course has some overhead because
microFocusChanged
is emitted multiple times, and in many cases, not just if an input field was selected (e.g. when selecting text).It probably would also make sense to do this in
loadFinished
because an element could be auto-focused.I haven't tested this yet, but intend to implement it soon.
If we only care about mouseclicks, extending
mousePressEvent
and doing ahitTestContent
there: