gpt4 book ai didi

python - 有没有办法同步调用方法 'toHtml' ,它是 QWebEnginePage 的对象?

转载 作者:行者123 更新时间:2023-12-03 23:17:37 54 4
gpt4 key购买 nike

我正在尝试从 QWebEnginePage 对象中获取 html 代码。根据 Qt 引用,QWebEnginePage 对象的 'toHtml' 是异步方法,如下所示。

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.



所以我试图找出如何同步调用这个方法。

我想要得到的结果如下。
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 不继续工作。

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *


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。

关于python - 有没有办法同步调用方法 'toHtml' ,它是 QWebEnginePage 的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47067050/

54 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com