在QWebEngineView浏览器中保存html文件
我正在尝试使用 Python QWebEngineView 创建自己的浏览器。我遵循了适用于 PyQt5 之前版本(2015 年左右)的教程,但由于最近的更新,之前代码的某些部分不再起作用。
我已经修复了大多数错误,但无法执行 html 文件打开/保存。当我单击“保存”按钮时,我总是收到系统错误。以下是我的文件保存代码:
(QMainWindow类)
save_file_action = QAction(QIcon("disk--pencil.png"), "Save Page As...", self)
save_file_action.setStatusTip("Save current page to file")
file_menu.addAction(save_file_action)
(save_file函数)
def save_file(self):
filename, _ = QFileDialog.getSaveFilename(self, "Save Page As", "",
"Hypertext Markup Language (*.htm *.html);;"
"All files(*.*)")
if filename:
html = self.browser.page().mainFrame().toHtml()
with open(filename, 'w') as f:
f.write(html)
谢谢。
I am trying to create my own browser using Python QWebEngineView . I have followed a tutorial that worked on an previous version of PyQt5 (around 2015), but due to its recent updates, some parts of the previous code no longer work.
I have fixed most errors but I am unable to perform html file opening/saving. I always receive a system error when I click on the save button. The following is my code for file saving:
(QMainWindow class)
save_file_action = QAction(QIcon("disk--pencil.png"), "Save Page As...", self)
save_file_action.setStatusTip("Save current page to file")
file_menu.addAction(save_file_action)
(save_file function)
def save_file(self):
filename, _ = QFileDialog.getSaveFilename(self, "Save Page As", "",
"Hypertext Markup Language (*.htm *.html);;"
"All files(*.*)")
if filename:
html = self.browser.page().mainFrame().toHtml()
with open(filename, 'w') as f:
f.write(html)
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
QtWebEngine
的toHtml()
函数是异步的,因此它不会直接返回任何内容,但您必须向其传递一个回调,以便在该函数中返回 html,将该进程异步转换为同步,我们在信号的帮助下使用QEventLoop
:the
toHtml()
function ofQtWebEngine
is asynchronous, so it does not return anything directly, but you have to pass it a callback so that in that function returns the html, to convert that process asynchronous to synchronous we use aQEventLoop
with the help of a signal :