PyQt Webkit和html表单:获取输出并关闭窗口 [英] PyQt Webkit and html forms: Fetching output and closing window

查看:87
本文介绍了PyQt Webkit和html表单:获取输出并关闭窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取无边界的python PyQt Webkit窗口,以显示单个网站html表单.单击发送"时,表单值应保存在词典中并关闭窗口.

I am trying to get a borderless python PyQt webkit window to display a single website html form. When clicking on send, the form values should be saved in a dictionnary and the window closed.

到目前为止(在 SO 的帮助下),我有了无边界窗口,可以获取输入.但是,缺少两件事:

So far (with the help of a SO) I have the borderless window and can fetch the input. However, two things are missing:

  1. 按发送"后关闭窗口.
  2. 获取字典elements中的输入(请注意,elements的键对应于html表单名称).
  1. Closing the window after pressing send.
  2. Fetching the input in the dictionary elements (note that the keys of elements correspond to the html form names).

(反过来可能会更好,但是1似乎更困难)

(potentially the other way round would be better, but 1 seems more difficult)

到目前为止,我的代码是:

My code so far is:

import sys

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *

elements = {"like":"", "text": ""}

class MyWebPage(QWebPage):
    def acceptNavigationRequest(self, frame, req, nav_type):
        if nav_type == QWebPage.NavigationTypeFormSubmitted:
            text = "<br/>\n".join(["%s: %s" % pair for pair in req.url().queryItems()])
            print(text)
            return True
        else:
            return super(MyWebPage, self).acceptNavigationRequest(frame, req, nav_type)


class Window(QWidget):
    def __init__(self, html):
        super(Window, self).__init__()
        self.setWindowFlags(Qt.FramelessWindowHint)
        view = QWebView(self)
        layout = QVBoxLayout(self)
        layout.addWidget(view)
        view.setPage(MyWebPage())
        view.setHtml(html)


# setup the html form
html = """
<form action="" method="get">
Like it?
<input type="radio" name="like" value="yes"/> Yes
<input type="radio" name="like" value="no" /> No
<br/><input type="text" name="text" value="Hello" />
<input type="submit" name="submit" value="Send"/>
</form>
"""

def main():
    app = QApplication(sys.argv)

    window = Window(html)
    window.show()
    app.exec_()

if __name__ == "__main__":
    main()

一个完美的答案不仅会显示如何(a)保存输入(b)关闭窗口,而且(c)还会删除html页面周围剩余的灰色小边框.

A perfect answer would not only show how to (a) save the input and (b) close the window, but (c) also remove the remaining small grey border around the html page.

更新:我使用Python 2.

Update: I use Python 2.

推荐答案

要将表单数据放入dict,最好使用

To get the form data into a dict, it is best to use unquote_plus from the python standard library as (unlike QUrl) it can handle plus-signs as well as percent-encoding.

要关闭窗口,您可以从网页发出formSubmitted信号,并将其连接到主窗口上的处理程序.然后,该处理程序可以在主窗口上调用close(),对表单数据进行所有处理,然后最后是quit()应用程序.

To close the window, you could emit a formSubmitted signal from the web-page, and connect it to a handler on the main-window. This handler could then call close() on the main-window, do all the processing of the form data, and then finally quit() the application.

要删除页面周围的边框,请设置 contentsMargins 设置为零.

To remove the border around the page, set the contentsMargins of the main layout to zero.

以下是您的脚本的修订版,实现了上述想法:

Here is revised version of your script which implements the above ideas:

import sys
from urllib import unquote_plus

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *

class MyWebPage(QWebPage):
    formSubmitted = pyqtSignal(QUrl)

    def acceptNavigationRequest(self, frame, req, nav_type):
        if nav_type == QWebPage.NavigationTypeFormSubmitted:
            self.formSubmitted.emit(req.url())
        return super(MyWebPage, self).acceptNavigationRequest(frame, req, nav_type)

class Window(QWidget):
    def __init__(self, html):
        super(Window, self).__init__()
        self.setWindowFlags(Qt.FramelessWindowHint)
        view = QWebView(self)
        layout = QVBoxLayout(self)
        layout.addWidget(view)
        layout.setContentsMargins(0, 0, 0, 0)
        view.setPage(MyWebPage())
        view.setHtml(html)
        view.page().formSubmitted.connect(self.handleFormSubmitted)

    def handleFormSubmitted(self, url):
        self.close()
        elements = {}
        for key, value in url.encodedQueryItems():
            key = unquote_plus(bytes(key)).decode('utf8')
            value = unquote_plus(bytes(value)).decode('utf8')
            elements[key] = value
        # do stuff with elements...
        for item in elements.iteritems():
            print '"%s" = "%s"' % item
        qApp.quit()

# setup the html form
html = """
<form action="" method="get">
Like it?
<input type="radio" name="like" value="yes"/> Yes
<input type="radio" name="like" value="no" /> No
<br/><input type="text" name="text" value="" />
<input type="submit" name="submit" value="Send"/>
</form>
"""

def main():
    app = QApplication(sys.argv)

    window = Window(html)
    window.show()
    app.exec_()

if __name__ == "__main__":
    main()

这篇关于PyQt Webkit和html表单:获取输出并关闭窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆