gpt4 book ai didi

python - 使用 QDesktopService 显示本地 html 文件

转载 作者:太空宇宙 更新时间:2023-11-03 21:41:51 25 4
gpt4 key购买 nike

我想在用户单击帮助图标时显示本地 html 文件。下面显示的方法连接到图标的触发信号。在下面显示的方法中,html 文件没有在我的默认浏览器中打开,并且脚本的 except 部分没有被激活。我有两个问题:

  1. 使用 PyQt5 显示本地 html 文件的最佳方法是什么?

  2. 如何让脚本在找不到 html 文件时抛出异常?

    def helpScreen(self):
    try:
    urlLink = QUrl.fromLocalFile(':/plugins/geomAttribute/help/index_en.html')
    QDesktopServices.openUrl(urlLink)
    except:
    QMessageBox.warning(None, 'Warning', 'Unable to locate help file')

最佳答案

为什么不显示 HTML?

路径以 : 开头,表示您正在使用 qresource ,您必须做的第一件事是使用以下命令将 .rc 转换为 .py:

pyrcc your_resource.qrc -o your_resource_rc.py

在我的例子中,我的qresource是resource.qrc,生成resource_rc.py文件,因此您必须将其导入到.py中。

qresource路径是虚拟的,它们不存在于硬盘中,所以当要使用该文件时浏览器将找不到它,所以解决方案是将其转换为本地文件,我们可以用QFile保存它但这个文件必须是临时的,所以最好用 QTemporaryFile 保存它。

在您的情况下,代码应如下所示:

from PyQt5 import QtCore, QtGui, QtWidgets


class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
lay = QtWidgets.QVBoxLayout(self)
button = QtWidgets.QPushButton("Help")
button.clicked.connect(self.helpScreen)
lay.addWidget(button)

def helpScreen(self):
resource_path = ":/plugins/geomAttribute/help/index_en.html"
resource_file = QtCore.QFile(resource_path)
if resource_file.open(QtCore.QIODevice.ReadOnly):
tmp_file = QtCore.QTemporaryFile(self)
tmp_file.setFileTemplate("XXXXXX.html")
if tmp_file.open():
tmp_file.write(resource_file.readAll())
resource_file.close()
tmp_file.flush()
url = QtCore.QUrl.fromLocalFile(tmp_file.fileName())
if QtGui.QDesktopServices.openUrl(url):
return
QtWidgets.QMessageBox.warning(None, 'Warning', 'Unable to locate help file')


import resource_rc


if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
<小时/>

<强>1。使用 PyQt5 显示本地 html 文件的最佳方法是什么?

显示 HTML 的方法有多种,最佳选择取决于您,例如有以下方法:

  • QDesktopServices::openUrl()
  • QLabel
  • QTextEditQPlainTextEdit
  • QWebEngineViewQWebView

<强>2。如何让脚本在找不到html文件时抛出异常?

出于效率原因,Qt 不会抛出异常,因此您不要在直接依赖于 Qt 的代码部分中使用 try-except,Qt 有 2 个主要机制来通知您错误(如果任务是同步的)该函数将返回一个 bool 值,指示任务是否正确完成,如果异步给出错误,将发出一个信号来指示它,在 QDesktopServices::openUrl() 的情况下是一个同步任务,因此它将返回一个 bool 值,指示任务是否执行成功:

bool QDesktopServices::openUrl(const QUrl &url)

Opens the given url in the appropriate Web browser for the user'sdesktop environment, and returns true if successful; otherwise returnsfalse.

[...]

关于python - 使用 QDesktopService 显示本地 html 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52798376/

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