如何在 QWebView/QWebPage 中获取焦点元素?

发布于 2024-09-01 09:11:52 字数 138 浏览 5 评论 0原文

我需要能够对 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

无声情话 2024-09-08 09:11:52

要处理页面中的任何 HTML 事件,请执行以下操作:

  1. 创建带有回调槽的 QObject 以接收事件。它可能是一些专用的处理程序对象或现有的对象,例如 QDialog/QMainWindow。
  2. 使用 QWebFrame.addToJavaScriptWindowObject(name, object) 注册用于 JavaScript 访问的 QObject。
  3. 编写 JavaScript 以添加 HTML 事件处理程序来调用已注册的 QObject 的回调槽。

添加焦点更改处理程序的 JavaScript 应遍历所有文本元素并添加 onfocus 和 onblur 处理程序。更好的方法是向 documentElement 添加单个处理程序并使用事件冒泡。不幸的是,onblur 广告 onfocus 不会冒泡。幸运的是,它们有一个名为 DOMFocusIn 和 DOMFocusOut 的冒泡对应项。

这是捕获页面文本元素的焦点输入/输出事件的完整示例。它在主窗口上声明了两个槽 handleFocusInhandleFocusOut,以便从 JavaScript 调用,并将主窗口注册为名为 MainWindow 的全局 JavaScript 变量。然后运行 ​​JavaScript 将 DOMFocusIn/DOMFocusOut 事件绑定到这些槽(间接地,因为我们需要过滤掉非文本元素)。

import sip
sip.setapi("QString", 2)
sip.setapi("QVariant", 2)
from PyQt4 import QtCore, QtGui, QtWebKit

class MyDialog(QtGui.QMainWindow):

    def __init__(self):
        super(MyDialog, self).__init__()
        self.setWindowTitle("QWebView JavaScript Events")

        web_view = QtWebKit.QWebView(self)
        web_view.setHtml("""
            <html>
                <body>
                    <input type="text" name="text1"/><br/>
                    <input type="text" name="text2"/><br/>
                    <input type="submit" value="OK"/>
                </body>
            </html>""")
        self.setCentralWidget(web_view)

        main_frame = web_view.page().mainFrame()
        main_frame.addToJavaScriptWindowObject("MainWindow", self)

        doc_element = main_frame.documentElement()
        doc_element.evaluateJavaScript("""
            function isTextElement(el) {
                return el.tagName == "INPUT" && el.type == "text";
            }
            this.addEventListener("DOMFocusIn", function(e) {
                if (isTextElement(e.target)) {
                    MainWindow.handleFocusIn(e.target.name);
                }
            }, false);
            this.addEventListener("DOMFocusOut", function(e) {
                if (isTextElement(e.target)) {
                    MainWindow.handleFocusOut(e.target.name);
                }
            }, false)
        """)

        self.resize(300, 150)

    @QtCore.pyqtSlot(QtCore.QVariant)
    def handleFocusIn(self, element_name):
        QtGui.QMessageBox.information(
            self, "HTML Event", "Focus In: " + element_name)

    @QtCore.pyqtSlot(QtCore.QVariant)
    def handleFocusOut(self, element_name):
        QtGui.QMessageBox.information(
            self, "HTML Event", "Focus Out: " + element_name)


app = QtGui.QApplication([])
dialog = MyDialog()
dialog.show()
app.exec_()

(如果你真的看不懂Python,我可以用C++重写)。

To handle any HTML event within a page you do the following:

  1. Create QObject with callback slots to receive the events. It may be some dedicated handler object or an existing object like your QDialog/QMainWindow.
  2. Register said QObject for JavaScript access with QWebFrame.addToJavaScriptWindowObject(name, object).
  3. Write JavaScript to add HTML event handlers that call your registered QObject's callback slots.

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 and handleFocusOut on the main window to be called from JavaScripts and registers main window as a global JavaScript variable named MainWindow. In then runs JavaScript to bind DOMFocusIn/DOMFocusOut events to these slots (indirectly, because we need to filter out non-text elemnts).

import sip
sip.setapi("QString", 2)
sip.setapi("QVariant", 2)
from PyQt4 import QtCore, QtGui, QtWebKit

class MyDialog(QtGui.QMainWindow):

    def __init__(self):
        super(MyDialog, self).__init__()
        self.setWindowTitle("QWebView JavaScript Events")

        web_view = QtWebKit.QWebView(self)
        web_view.setHtml("""
            <html>
                <body>
                    <input type="text" name="text1"/><br/>
                    <input type="text" name="text2"/><br/>
                    <input type="submit" value="OK"/>
                </body>
            </html>""")
        self.setCentralWidget(web_view)

        main_frame = web_view.page().mainFrame()
        main_frame.addToJavaScriptWindowObject("MainWindow", self)

        doc_element = main_frame.documentElement()
        doc_element.evaluateJavaScript("""
            function isTextElement(el) {
                return el.tagName == "INPUT" && el.type == "text";
            }
            this.addEventListener("DOMFocusIn", function(e) {
                if (isTextElement(e.target)) {
                    MainWindow.handleFocusIn(e.target.name);
                }
            }, false);
            this.addEventListener("DOMFocusOut", function(e) {
                if (isTextElement(e.target)) {
                    MainWindow.handleFocusOut(e.target.name);
                }
            }, false)
        """)

        self.resize(300, 150)

    @QtCore.pyqtSlot(QtCore.QVariant)
    def handleFocusIn(self, element_name):
        QtGui.QMessageBox.information(
            self, "HTML Event", "Focus In: " + element_name)

    @QtCore.pyqtSlot(QtCore.QVariant)
    def handleFocusOut(self, element_name):
        QtGui.QMessageBox.information(
            self, "HTML Event", "Focus Out: " + element_name)


app = QtGui.QApplication([])
dialog = MyDialog()
dialog.show()
app.exec_()

(I may rewrite in in C++ if you REALLY can't figure out Python).

知你几分 2024-09-08 09:11:52

我遇到了同样的问题,但不想使用 Javascript ,因为我希望它即使在 QWebSettings 中禁用 javascript 的情况下也能工作。我基本上可以想到两种方法:

  • 按照建议监听 microFocusChanged 信号,然后执行以下操作:

    frame = page.currentFrame()
    elem =frame.findFirstElement('输入:not([type=hidden]):焦点文本区域:焦点')
    如果不是 elem.isNull():
        logging.debug("点击了可编辑元素!")
    

    这当然会产生一些开销,因为 microFocusChanged 会被多次发出,而且在许多情况下,不仅仅是在选择输入字段时(例如,在选择文本时)。

    loadFinished 中执行此操作可能也有意义,因为元素可以自动聚焦。

    我还没有测试过这个,但打算很快实现它。

  • 如果我们只关心鼠标点击,则扩展mousePressEvent并在那里执行hitTestContent

    def mousePressEvent(self, e):
        pos = e.pos()
        框架 = self.page().frameAt(pos)
        pos -=frame.geometry().topLeft()
        hitresult =frame.hitTestContent(pos)
        如果 hitresult.isContentEditable():
            logging.debug("点击了可编辑元素!")
        返回 super().mousePressEvent(e)
    

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:

    frame = page.currentFrame()
    elem = frame.findFirstElement('input:not([type=hidden]):focus textarea:focus')
    if not elem.isNull():
        logging.debug("Clicked editable element!")
    

    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 a hitTestContent there:

    def mousePressEvent(self, e):
        pos = e.pos()
        frame = self.page().frameAt(pos)
        pos -= frame.geometry().topLeft()
        hitresult = frame.hitTestContent(pos)
        if hitresult.isContentEditable():
            logging.debug("Clicked editable element!")
        return super().mousePressEvent(e)
    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文