简体   繁体   中英

Parse and Display HTML in a QTextEdit widget

I have a non-editable QTextEdit Widget in one of my apps. Basend on the selection of a combobox i want to display additional informations.

My current approach is to load HTML files from a directory and display them in the QTextEdit-Field. This sounds easy (with the functions setHtml or insertHtml), but somehow doesn't work as straight forward as i thought. I believe i have to parse or load in the file first. How can i continue?

h = (helpdir + str + ".html") # contains the helpfiles path (Format QString)
# Load in HTML?
textfield.insertHtml(h) # Should somehow insert the html

Other approaches (especially in the light of a future translation of the help), which are easy to implement, are welcome. I would favor any solution without additional libraries or non base packages.

Yes, you have to load the HTML file before inserting it into the QTextEdit . But doing it is pretty easy:

    f = QFile("path/to/your/htmlfile")
    f.open(QFile.ReadOnly|QFile.Text)
    istream = QTextStream(f)
    textfield.setHtml(istream.readAll())
    f.close()

It works just fine (assuming that your HTML file is not very large). You can also read the file line by line if it fits better your needs.

you can use QtWebKit it's the best way to go with html content in qt. It should come with your python qt install. check out the code below:

test.py

import sys
from PyQt4 import QtCore, QtGui, QtWebKit

app = QtGui.QApplication(sys.argv)
view = QtWebKit.QWebView()
view.setHtml(open('test.html').read())
window = QtGui.QMainWindow()
window.setCentralWidget(view)
window.show()
sys.exit(app.exec_())

test.html

<html><body><h1>test page</h1>testing...</body></html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM