3

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().

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

1 Comment

thanks once again @ekhumoro.. I'm new in Gui programming and PyQt4..so dont mind if my questions are stupid... your solutions works well..thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.