目录
1. 使用 append 方法:
2. 使用 setPlainText 方法
3.例子:
1. 使用 append
方法:
如果你希望在 QTextEdit
控件上追加显示新的信息,可以使用 append
方法。例如,当你想要追加一行新的日志信息:
self.text_edit.append("This is a new log message")
2. 使用 setPlainText
方法
如果你希望设置或替换整个 QTextEdit
控件的文本内容,可以使用 setPlainText
方法:
self.text_edit.setPlainText("This is the new content replacing any existing content")
3.例子:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QTextEdit, QPushButton, QHBoxLayoutclass MainWindow(QMainWindow):def __init__(self):super().__init__()self.initUI()def initUI(self):self.setWindowTitle("Text Display Example")self.text_edit = QTextEdit(self)self.text_edit.setReadOnly(True)# Create buttonsself.append_button = QPushButton("Append Text", self)self.append_button.clicked.connect(self.append_text)self.set_text_button = QPushButton("Set Plain Text", self)self.set_text_button.clicked.connect(self.set_plain_text)# Create layout for buttonsbutton_layout = QHBoxLayout()button_layout.addWidget(self.append_button)button_layout.addWidget(self.set_text_button)# Create main layoutlayout = QVBoxLayout()layout.addWidget(self.text_edit)layout.addLayout(button_layout)# Set the main layout to a central widgetcontainer = QWidget()container.setLayout(layout)self.setCentralWidget(container)def append_text(self):""" Append text to the QTextEdit """self.text_edit.append("Appended Text: This is a new line of text.")def set_plain_text(self):""" Set plain text to the QTextEdit """self.text_edit.setPlainText("Set Plain Text: This text replaces all existing text.")# Main code to start the application
if __name__ == "__main__":app = QApplication(sys.argv)window = MainWindow()window.show()sys.exit(app.exec_())