【问题标题】:PyQt4: QtWebKit display local file using the Qt resource systemPyQt4:QtWebKit使用Qt资源系统显示本地文件
【发布时间】:2012-09-04 20:18:07
【问题描述】:

如何使用 Qt 资源系统显示本地 html 文件?明显的QtCore.QUrl.fromLocalFile(":/local_file.html") 似乎不是正确的语法。

文件 mainwindow.qrc(编译前)

<qresource prefix="/">
    <file alias="html_home">webbrowser_html/program_index.html</file>

文件ui_mainwindow:

class Ui_MainWindow(object):    
    def setupUi(self, MainWindow):
        #...
        self.WebBrowser = QtWebKit.QWebView(self.Frame3)

文件 webbrower.py

from ui_mainwindow import Ui_MainWindow
import mainwindow_rc

class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        self.setupUi(self)
        #...
        stream = QtCore.QFile(':/webbrowser_html/program_index.html')
        if stream.open(QtCore.QFile.ReadOnly):
            home_html = QtCore.QString.fromUtf8(stream.readAll())
            self.WebBrowser.setHtml()
            stream.close()

【问题讨论】:

    标签: python url resources pyqt4 local


    【解决方案1】:

    QUrl 需要一个方案,对于资源,它是qrc://。相关部分来自docs

    默认情况下,资源在同一应用下是可以访问的 源树中的文件名,带有 :/ 前缀,或 带有 qrc 方案的 URL。

    例如,文件路径 :/images/cut.png 或 URL qrc:///images/cut.png 将允许访问 cut.png 文件,其 在应用程序的源代码树中的位置是images/cut.png

    所以,改用这个:

    QtCore.QUrl("qrc:///local_file.html")
    

    编辑

    您正在为文件提供alias (alias="html_home"):

    <qresource prefix="/">
        <file alias="html_home">webbrowser_html/program_index.html</file>
    

    路径现在是:/html_home,而不是:/webbrowser_html/program_index.html

    你应该使用:

    QtCore.QUrl("qrc:///html_home")
    

    你的情况是这样的:

    class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
        def __init__(self):
            QtGui.QMainWindow.__init__(self)
    
            self.setupUi(self)
            #...
            self.WebBrowser.load(QtCore.QUrl('qrc:///html_home'))
    

    (如果您打算使用 ekhumoro's solution,您也应该调整它。另外请注意,您没有在粘贴中设置页面的 HTML。)

    【讨论】:

    • @XianJacobs:您能发布一下您是如何使用这些解决方案的吗?
    【解决方案2】:

    本地资源文件可以用QFile打开:

    stream = QFile(':/local_file.html')
    if stream.open(QFile.ReadOnly):
        self.browser.setHtml(QString.fromUtf8(stream.readAll()))
        stream.close()
    

    【讨论】:

    • @X.Jacobs。您的示例代码没有将home_html 传递给self.WebBrowser.setHtml()
    猜你喜欢
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    相关资源
    最近更新 更多