[英]Parse and Display HTML in a QTextEdit widget
我的一個應用程序中有一個不可編輯的QTextEdit小部件。 基於對組合框的選擇,我想顯示其他信息。
我當前的方法是從目錄加載HTML文件,並將其顯示在QTextEdit-Field中。 這聽起來很簡單(使用setHtml或insertHtml函數),但是某種程度上不像我想的那樣直接。 我相信我必須先解析或加載文件。 我該如何繼續?
h = (helpdir + str + ".html") # contains the helpfiles path (Format QString)
# Load in HTML?
textfield.insertHtml(h) # Should somehow insert the html
歡迎使用其他易於實現的方法(尤其是根據將來對幫助的翻譯)。 我希望沒有其他庫或非基本軟件包的任何解決方案。
是的,您必須先加載HTML文件,然后才能將其插入QTextEdit
。 但是這樣做很容易:
f = QFile("path/to/your/htmlfile")
f.open(QFile.ReadOnly|QFile.Text)
istream = QTextStream(f)
textfield.setHtml(istream.readAll())
f.close()
它工作正常(假設您的HTML文件不是很大)。 如果更適合您的需求,您也可以逐行讀取文件。
您可以使用QtWebKit,這是在qt中處理html內容的最佳方法。 它應該隨python qt安裝一起提供。 查看以下代碼:
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.