How to display simple html file in Qt
Asked Answered
C

2

7

I'm looking for the easiest way to display a simple html file (just a long html-formatted text) inside the Qt dialog. Links, if any, should be opened in the external default system browser.

Cocainism answered 14/12, 2016 at 8:48 Comment(0)
T
16

No need for a QWebView, use a QTextBrowser:

#include <QTextBrowser>
QTextBrowser *tb = new QTextBrowser(this);
tb->setOpenExternalLinks(true);
tb->setHtml(htmlString);

also remember QT += widgets

http://doc.qt.io/qt-5/qtextedit.html#html-prop

http://doc.qt.io/qt-5/qtextbrowser.html#openExternalLinks-prop

Thermochemistry answered 14/12, 2016 at 9:51 Comment(3)
Works. Thanks a lot!Cocainism
import codecs f=codecs.open(r"D:\filename.html", 'r') tb = QTextBrowser() tb.setOpenExternalLinks(True) tb.setHtml(f.read()) tb.show()Pinfeather
Note QTextBrowser isn't dysplaying a correct html. It displays it as formatted hypertext in SGML-like format with tag system loosely resembling html4. It might be an ill-formed html and it still would be displayed. It can't do most things html browser does.Botanical
B
5

Working example in Python using PySide2:

from PySide2.QtWidgets import QTextBrowser, QApplication


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)

    text_browser = QTextBrowser()
    str_html = """
        <!DOCTYPE html>
        <html>
        <body>

        <h1 style="color:blue;">Hello World!</h1>
        <p style="color:red;">Lorem ipsum dolor sit amet.</p>

        </body>
        </html>
        """
    text_browser.setText(str_html)
    text_browser.show()
    text_browser.raise_()

    sys.exit(app.exec_())
Billings answered 14/1, 2020 at 16:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.