目錄
1、QTextEdit控件介紹
2、QTextEdit控件添加文本、添加HTML格式
3、QTextEdit控件獲取文本、獲取HTML格式文本
4、案例
1)完整代碼
?2)效果
1、QTextEdit控件介紹
QTextEdit控件是一個支持多行輸入的輸入框,支持HTML進行格式的設置
2、QTextEdit控件添加文本、添加HTML格式
# 顯示文本 def showText(self):self.textedit.setPlainText("hello world")# 顯示HTML def showHTML(self):self.textedit.setHtml('<font color="blue" size="5">Hello World</font>')
注意:這里的添加文本的方式會先將文本框清空再進行添加,若想要追加,則可以使用append方法
?self.textedit.append(要追加的字符串格式的內容)
3、QTextEdit控件獲取文本、獲取HTML格式文本
# 獲取文本 def getText(self):print(self.textedit.toPlainText())# 獲取HTML def getHTML(self):print(self.textedit.toHtml())
4、案例
1)完整代碼
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2022/5/24 14:52
# @Author : @linlianqin
# @Site :
# @File : QTextEdit_learn.py
# @Software: PyCharm
# @description:from PyQt5.QtWidgets import *class qtexteditlearn(QWidget):def __init__(self):super(qtexteditlearn, self).__init__()self.InitUI()def InitUI(self):self.setWindowTitle("qtexteditlearn")self.textedit = QTextEdit()self.button1 = QPushButton("顯示文本")self.button2 = QPushButton("顯示HTML")self.button3 = QPushButton("獲取文本")self.button4 = QPushButton("獲取HTML")self.resize(300,280)layout = QVBoxLayout()layout.addWidget(self.textedit)layout.addWidget(self.button1)layout.addWidget(self.button2)layout.addWidget(self.button3)layout.addWidget(self.button4)self.button1.clicked.connect(self.showText)self.button2.clicked.connect(self.showHTML)self.button3.clicked.connect(self.getText)self.button4.clicked.connect(self.getHTML)self.setLayout(layout)# 獲取文本def getText(self):print(self.textedit.toPlainText())# 獲取HTMLdef getHTML(self):print(self.textedit.toHtml())# 顯示文本def showText(self):self.textedit.setPlainText("hello world")# 顯示HTMLdef showHTML(self):self.textedit.setHtml('<font color="blue" size="5">Hello World</font>')if __name__ == '__main__':import sysapp = QApplication(sys.argv)mainWin = qtexteditlearn()mainWin.show()sys.exit(app.exec_())
?2)效果
# 獲取文本結果
Hello World
# 獲取HTML結果
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'SimSun'; font-size:9pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:x-large; color:#0000
ff;">Hello World</span></p></body></html>?
?