QTextEdit 类是一个多行文本框控件, 可以显示多行文本内容, 当文本内容超出控件显示范围时, 可以显示水平个垂直滚动条, Qtextedit 不仅可以用来显示文本还可以用来显示 html 文档
- import sys
- from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QTextEdit, QTextBrowser, QHBoxLayout, QVBoxLayout
- class Demo(QWidget):
- def __init__(self):
- super(Demo, self).__init__()
- self.edit_label = QLabel('文本编辑框 QTextEdit', self)
- self.browser_label = QLabel('文本浏览框 QTextBrowser', self)
- self.text_edit = QTextEdit(self) #实例化文本编辑框
- self.text_browser = QTextBrowser(self) #实例化文本浏览框
- self.edit_v_layout = QVBoxLayout()
- self.browser_v_layout = QVBoxLayout()
- self.all_h_layout = QHBoxLayout()
- self.layout_init()
- self.text_edit_init()
- self.text_edit.setPlainText('我是李明 \ n 我是物理教师') #设置文本编辑框的内容
- #self.text_edit.clear() #清楚文本编辑框的内容
- def layout_init(self):
- self.edit_v_layout.addWidget(self.edit_label)
- self.edit_v_layout.addWidget(self.text_edit)
- self.browser_v_layout.addWidget(self.browser_label)
- self.browser_v_layout.addWidget(self.text_browser)
- self.all_h_layout.addLayout(self.edit_v_layout)
- self.all_h_layout.addLayout(self.browser_v_layout)
- self.setLayout(self.all_h_layout)
- def text_edit_init(self):
- self.text_edit.textChanged.connect(self.show_text_func) #文本内容发生变化时
- def show_text_func(self):# 文本内容发生变化时的槽函数
- self.text_browser.setText(self.text_edit.toPlainText()) #toPlainText() 返回文本编辑框的内容
- #setText() 设置文本浏览框的内容
- if __name__ == '__main__':
- App = QApplication(sys.argv)
- demo = Demo()
- demo.show()
- sys.exit(App.exec_())
来源: http://www.bubuko.com/infodetail-2948249.html