PyQt4: QtWebKit displays a local file using the Qt resource system

How would you display a local html file using the Qt resource system? The obvious QtCore.QUrl.fromLocalFile(":/local_file.html") not the correct syntax.

Mainwindow.qrc file (before compilation)

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

Ui_mainwindow file:

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

File 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() 
+4
source share
2 answers

QUrl requires a schema, and qrc:// for resources. Relevant part of the docs :

By default, resources are available in the application under the same file name as it is in the source tree, with the prefix :/ or URL using the qrc scheme.

For example, the path to the file :/images/cut.png or the URL qrc:///images/cut.png will provide access to the cut.png file, whose location in the application source tree is images/cut.png .

So use this instead:

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

Edit

You pass the alias file ( alias="html_home" ):

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

Now the path :/html_home , and not :/webbrowser_html/program_index.html

You should use:

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

What will happen in your case:

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

(You should also adjust the ekhumoro solution if you intend to use this. Also note that you are not setting the HTML code of the page in the paste.)

+7
source

Local resource files can be opened using QFile :

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

Source: https://habr.com/ru/post/1433654/


All Articles