简体   繁体   English

在QTextEdit小部件中解析并显示HTML

[英]Parse and Display HTML in a QTextEdit widget

I have a non-editable QTextEdit Widget in one of my apps. 我的一个应用程序中有一个不可编辑的QTextEdit小部件。 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. 我当前的方法是从目录加载HTML文件,并将其显示在QTextEdit-Field中。 This sounds easy (with the functions setHtml or insertHtml), but somehow doesn't work as straight forward as i thought. 这听起来很简单(使用setHtml或insertHtml函数),但是某种程度上不像我想的那样直接。 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 . 是的,您必须先加载HTML文件,然后才能将其插入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). 它工作正常(假设您的HTML文件不是很大)。 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. 您可以使用QtWebKit,这是在qt中处理html内容的最佳方法。 It should come with your python qt install. 它应该随python qt安装一起提供。 check out the code below: 查看以下代码:

test.py 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 test.html

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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