QTextEdit插入图片insertImage()、QTextImageFormat ()和插入文件QTextDocumentFragment()
QTextEdit除了插入文本内容外,图片和文件都可以直接插入其中,本章节就通过insertImage()、QTextImageFormat ()来插入流媒体图片,通过QTextDocumentFragment()、insertFragment()来插入文件。
QTextEdit除了插入文本内容外,图片和文件都可以直接插入其中,本章节就通过insertImage()、QTextImageFormat ()来插入流媒体图片,通过QTextDocumentFragment()、insertFragment()来插入文件。
既然是通过文本光标来插入素材,首先还是要创建光标对象,用光标对象来给插入内容进行格式加工。
一、文本光标插入图片insertImage()、QTextImageFormat ()
1.创建光标对象
qtc = self.qte.textCursor()
2.设置图片内容的格式
tcf = QTextImageFormat() tcf.setName('123.jpg') tcf.setWidth(40) tcf.setHeight(40)
3.插入图片,并传入格式
qtc.insertImage(tcf)
二、QTextDocumentFragment()、insertFragment()插入文件
1.创建光标对象
qtc = self.qte.textCursor()
2.设置文件格式
tcf = QTextDocumentFragment().fromHtml("<a href='https://www.pyqt5.cn'>PyQt5中文网</a>") # 插入富文本 # tcf.fromHtml("<a href='https://www.pyqt5.cn'>PyQt5中文网</a>") # fromHtml有返回值,所以必须给个变量名,这样写就错了 # tcf = QTextDocumentFragment().fromPlainText("<a href='https://www.pyqt5.cn'>PyQt5中文网</a>") # 插入普通文本
3.插入文件传入格式
qtc.insertFragment(tcf)
下面是完整代码:
from PyQt5.Qt import * import sys class Window(QWidget): def __init__(self): super().__init__() self.setWindowTitle("QTextEdit - PyQt5中文网") self.resize(600, 500) self.func_list() def func_list(self): self.func() def func(self): self.qte = QTextEdit('QTextEdit构造', self) self.qte.move(100, 100) self.qte.resize(250, 250) self.btn = QPushButton('按 钮', self) self.btn.move(120, 50) self.btn.resize(70, 30) self.btn.pressed.connect(self.text_cur) # 文本光标完成内容和格式设置 def text_cur(self): # # 1.首先创建一个光标对象 # qtc = self.qte.textCursor() # # 3.插入图片内容格式 # tcf = QTextImageFormat() # tcf.setName('123.jpg') # tcf.setWidth(40) # tcf.setHeight(40) # # 2.通过光标插入文本,传入上面的格式对象 # qtc.insertImage(tcf) qtc = self.qte.textCursor() # 3.插入文件内容格式 tcf = QTextDocumentFragment().fromHtml("<a href='https://www.pyqt5.cn'>PyQt5中文网</a>") # 插入富文本 # tcf.fromHtml("<a href='https://www.pyqt5.cn'>PyQt5中文网</a>") # fromHtml有返回值,所以必须给个变量名,这样写就错了 # tcf = QTextDocumentFragment().fromPlainText("<a href='https://www.pyqt5.cn'>PyQt5中文网</a>") # 插入普通文本 # 2.通过光标插入文本,传入上面的格式对象 qtc.insertFragment(tcf) if __name__ == '__main__': app = QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec_())