有什么方法可以同步调用QWebEnginePage对象的"toHtml"方法吗? [英] Is there any way to call synchronously the method 'toHtml' which is QWebEnginePage's object?
问题描述
我正在尝试从QWebEnginePage对象获取html代码.根据Qt参考,QWebEnginePage对象的'toHtml'是异步方法,如下所示.
I'm trying to get html code from the QWebEnginePage object. According to Qt reference, QWebEnginePage object's 'toHtml' is asynchronous method as below.
异步方法,以HTML和BODY标记括起来以HTML格式检索页面的内容.成功完成后,将使用页面的内容调用resultCallback.
Asynchronous method to retrieve the page's content as HTML, enclosed in HTML and BODY tags. Upon successful completion, resultCallback is called with the page's content.
所以我试图找出如何同步调用此方法.
so I tried to find out how call this method synchronously.
我想要得到的结果如下.
the result what i want to get is below.
class MainWindow(QWidget):
html = None
...
...
def store_html(self, data):
self.html = data
def get_html(self):
current_page = self.web_view.page()
current_page.toHtml(self.store_html)
# I want to wait until the 'store_html' method is finished
# but the 'toHtml' is called asynchronously, return None when try to return self.html value like below.
return self.html
...
...
感谢您阅读本文.
祝大家有美好的一天.
推荐答案
获得该行为的简单方法是使用 QEventLoop()
.此类的对象阻止执行exec_()
之后的代码,这并不意味着GUI无法继续工作.
A simple way to get that behavior is to use QEventLoop()
. An object of this class prevents the code that is after exec_()
from being executed, this does not mean that the GUI does not continue working.
class Widget(QWidget):
toHtmlFinished = pyqtSignal()
def __init__(self, *args, **kwargs):
QWidget.__init__(self, *args, **kwargs)
self.setLayout(QVBoxLayout())
self.web_view = QWebEngineView(self)
self.web_view.load(QUrl("http://doc.qt.io/qt-5/qeventloop.html"))
btn = QPushButton("Get HTML", self)
self.layout().addWidget(self.web_view)
self.layout().addWidget(btn)
btn.clicked.connect(self.get_html)
self.html = ""
def store_html(self, html):
self.html = html
self.toHtmlFinished.emit()
def get_html(self):
current_page = self.web_view.page()
current_page.toHtml(self.store_html)
loop = QEventLoop()
self.toHtmlFinished.connect(loop.quit)
loop.exec_()
print(self.html)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
注意:相同的方法适用于PySide2.
Note: The same method works for PySide2.
这篇关于有什么方法可以同步调用QWebEnginePage对象的"toHtml"方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!