Reputation: 443
I'm creating an application using PyQt4 to be able to view an inline text HTML mark-up without loading a local HTML file from the system. But, i got some problem with the string format of the HTML.This code is showing only the Window not the HTML text. Please help.
# imported all the modules class HtmlView(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) ................. # i've skipped the layout definition here ................ # an inline text with html mark-up text = "<p>This is a paragraph</p><div>This is inside div element</div>" self.html = QtWebKit.QWebView() # setting layout self.gridLayout.addWidget(self.html) self.mainLayout.addWidget(self.frame) self.setCentralWidget(self.centralwidget) self.web_page = text url = self.web_page self.html.load(QtCore.QUrl(url)) self.html.show() # executing using if __name__ == "main": skipped this part
And please tell me how to change the style of elements <p> and <div> inside the QWebView().
Upvotes: 3
Views: 3956
Reputation: 120778
You need to use setHtml to load markup in the webview:
self.html = QtWebKit.QWebView()
# self.web_page = text
# url = self.web_page
self.html.setHtml(text)
# self.html.show()
(The commented lines aren't needed).
To style the elements, add a stylesheet to your markup:
text = """
<html>
<style type="text/css">
p {color: red}
div {color: blue}
</style>
<body>
<p>This is a paragraph</p>
<div>This is inside div element</div>
</body>
</html>
"""
PS: using a QWebView for displaying markup is a very heavy-weight solution - it might be better to use QTextBrowser instead (which is much easier to use). This only has support for a limited subset of HTML, but it is usually good enough:
self.html = QtGui.QTextBrowser(self)
self.html.setHtml(text)
Upvotes: 5