漳州做网站最便宜,私募网站建设,网站入口类型,重庆专业网站设计服务文字输入类控件用于接收用户文本 / 数值输入#xff0c;是表单、设置界面的核心组件。1. QLineEdit#xff08;单行文本框#xff09;核心作用#xff1a;单行文本输入#xff08;如用户名、密码、搜索框#xff09;。关键特性#xff1a;密码模式#xff1a;setEchoMo…文字输入类控件用于接收用户文本 / 数值输入是表单、设置界面的核心组件。1. QLineEdit单行文本框核心作用单行文本输入如用户名、密码、搜索框。关键特性密码模式setEchoMode(QLineEdit.Password)输入验证通过 QValidator 限制输入格式整数、浮点数、正则占位符提示setPlaceholderText(请输入用户名)信号textChanged(str)实时变化、editingFinished()输入完成。输入验证示例import sys from PySide6.QtWidgets import QLineEdit, QApplication app QApplication(sys.argv) line_edit QLineEdit() # 仅允许输入数字 line_edit.setPlaceholderText(请输入数字) # 设置占位符 def on_text_changed(text): if not text.isdigit(): print(输入错误请修改) line_edit.setStyleSheet(color: red) else: line_edit.setStyleSheet(color: black) line_edit.textChanged.connect(on_text_changed) line_edit.show() app.exec()2. QPlainTextEdit纯文本框QPlainTextEdit 是 PySide6 中用于编辑和显示纯文本的控件专为处理大文本文件优化相比 QTextEdit 更轻量无富文本渲染开销支持行号、语法高亮、撤销 / 重做、文本选择、滚动等核心功能是编写日志查看器、代码编辑器、纯文本编辑器的首选控件。核心特性轻量级纯文本处理仅处理纯文本无富文本如字体 / 颜色 / 图片渲染性能优于 QTextEdit行级操作便捷的行增删、行内容获取 / 修改编辑功能默认支持撤销、重做、复制、粘贴、剪切滚动与视图支持自动滚动、光标定位、可见区域控制信号与槽文本变化、光标移动、选择变化等信号便于交互逻辑实现自定义扩展可结合 QSyntaxHighlighter 实现语法高亮结合 QAbstractScrollArea 自定义滚动条 / 行号。基本使用1. 基础初始化与布局import sys from PySide6.QtWidgets import (QApplication, QMainWindow, QPlainTextEdit, QVBoxLayout, QWidget) class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle(QPlainTextEdit 示例) self.resize(800, 600) # 1. 创建 QPlainTextEdit 实例 self.text_edit QPlainTextEdit() # 2. 基础配置 self.text_edit.setPlaceholderText(请输入纯文本内容...) # 占位提示 self.text_edit.setReadOnly(False) # 是否只读True 则无法编辑 self.text_edit.setLineWrapMode(QPlainTextEdit.NoWrap) # NoWrap不自动换行默认 # QPlainTextEdit.WidgetWidth按控件宽度自动换行 # 3. 设置中心部件 central_widget QWidget() layout QVBoxLayout(central_widget) layout.addWidget(self.text_edit) self.setCentralWidget(central_widget) if __name__ __main__: app QApplication(sys.argv) window MainWindow() window.show() sys.exit(app.exec())2. 文本操作核心方法方法功能示例setPlainText(text)设置全部文本覆盖原有内容self.text_edit.setPlainText(Hello PySide6!)toPlainText()获取全部文本返回字符串text self.text_edit.toPlainText()insertPlainText(text)在光标位置插入文本不覆盖self.text_edit.insertPlainText(插入的内容)appendPlainText(text)在末尾追加文本自动换行self.text_edit.appendPlainText(新行内容)clear()清空所有文本self.text_edit.clear()undo()/redo()撤销 / 重做操作self.text_edit.undo()copy()/cut()/paste()复制 / 剪切 / 粘贴self.text_edit.copy()行级操作高频需求import sys from PySide6.QtGui import QTextCursor from PySide6.QtWidgets import (QApplication, QMainWindow, QPlainTextEdit, QVBoxLayout, QWidget) class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle(QPlainTextEdit 示例) self.resize(800, 600) # 1. 创建 QPlainTextEdit 实例 self.text_edit QPlainTextEdit() # 2. 基础配置 self.text_edit.setPlainText(line0\n line1\n line2\n line3\n line4\n line5\n line6\n) self.text_edit.setReadOnly(False) # 是否只读True 则无法编辑 self.text_edit.setLineWrapMode(QPlainTextEdit.NoWrap) # NoWrap不自动换行默认 # QPlainTextEdit.WidgetWidth按控件宽度自动换行 # 获取当前光标所在行号从 0 开始 # current_line self.text_edit.textCursor().blockNumber() # print(current_line) # 3. 设置中心部件 central_widget QWidget() layout QVBoxLayout(central_widget) layout.addWidget(self.text_edit) self.setCentralWidget(central_widget) # 获取指定行内容行号从 0 开始 def get_line_content(self, line_num): block self.text_edit.document().findBlockByNumber(line_num) return block.text() if block.isValid() else # 修改指定行内容 def set_line_content(self, line_num, new_text): cursor self.text_edit.textCursor() block self.text_edit.document().findBlockByNumber(line_num) if block.isValid(): cursor.setPosition(block.position()) # 定位到行首 cursor.select(QTextCursor.SelectionType.BlockUnderCursor) # 选中整行 cursor.insertText(new_text) # 替换内容 # 删除指定行 def delete_line(self, line_num): cursor self.text_edit.textCursor() block self.text_edit.document().findBlockByNumber(line_num) if block.isValid(): cursor.setPosition(block.position()) cursor.select(QTextCursor.SelectionType.BlockUnderCursor) cursor.removeSelectedText() # 删除选中内容 # 移除多余的换行符可选 # cursor.deleteChar() if __name__ __main__: app QApplication(sys.argv) window MainWindow() print(f第一行内容:, window.get_line_content(1)) # 获取第二行内容 window.set_line_content(1, \n新内容1) # 修改第二行内容 print(f第一行内容:, window.get_line_content(1)) # 获取第二行内容 window.delete_line(3) window.show() sys.exit(app.exec())光标与选择控制QPlainTextEdit 的光标操作依赖QTextCursor可实现精准的文本定位、选择、编辑# 获取当前光标对象 cursor self.text_edit.textCursor() # 1. 光标定位 cursor.movePosition(cursor.Start) # 移到文本开头 cursor.movePosition(cursor.End) # 移到文本结尾 cursor.movePosition(cursor.Down, cursor.MoveAnchor, 5) # 向下移动5行 self.text_edit.setTextCursor(cursor) # 应用光标位置 # 2. 文本选择 cursor.setPosition(10) # 起始位置 cursor.movePosition(cursor.Right, cursor.KeepAnchor, 5) # 向右选择5个字符 selected_text cursor.selectedText() # 获取选中的文本 # 3. 替换选中的文本 cursor.insertText(替换后的内容) # 4. 选中所有文本 self.text_edit.selectAll()信号与槽核心交互QPlainTextEdit 提供丰富的信号用于响应文本变化、光标移动等事件信号触发条件textChanged()文本内容发生变化时每次输入 / 删除字符都会触发cursorPositionChanged()光标位置改变时selectionChanged()选中的文本范围改变时undoAvailable(bool)撤销操作可用 / 不可用时redoAvailable(bool)重做操作可用 / 不可用时示例响应文本变化和光标移动import sys from PySide6.QtCore import QMetaObject, Slot from PySide6.QtWidgets import QPlainTextEdit, QApplication class MyTextEdit(QPlainTextEdit): def __init__(self, parentNone): super().__init__(parent) self.setupUI() QMetaObject.connectSlotsByName(self) def setupUI(self): self.textChanged.connect(self.on_textChanged) self.cursorPositionChanged.connect(self.on_cursorPositionChanged) Slot() def on_textChanged(self): 文本变化时触发统计字符数和行数 text self.toPlainText() char_count len(text) line_count self.document().blockCount() self.setWindowTitle(f字符数{char_count} | 行数{line_count}) Slot() def on_cursorPositionChanged(self): 光标移动时触发显示当前行/列 cursor self.textCursor() line cursor.blockNumber() 1 # 行号从1开始显示 col cursor.columnNumber() 1 # 列号从1开始显示 print(f当前位置第 {line} 行第 {col} 列) app QApplication(sys.argv) text_edit MyTextEdit() text_edit.show() sys.exit(app.exec())高级配置1. 换行模式控制文本超出控件宽度时的换行行为# 可选模式 # NoWrap不换行横向滚动条出现 # WidgetWidth按控件宽度自动换行默认 # FixedPixelWidth按固定像素宽度换行 # FixedColumnWidth按固定字符数换行 self.text_edit.setLineWrapMode(QPlainTextEdit.WidgetWidth)2. 滚动控制# 自动滚动到末尾如日志输出场景 self.text_edit.verticalScrollBar().setValue( self.text_edit.verticalScrollBar().maximum() ) # 滚动到指定行 def scroll_to_line(line_num): block self.text_edit.document().findBlockByNumber(line_num) if block.isValid(): self.text_edit.scrollToBlock(block)3. 只读模式与编辑权限self.text_edit.setReadOnly(True) # 只读无法编辑可选中/复制 self.text_edit.setUndoRedoEnabled(False) # 禁用撤销/重做 self.text_edit.setAcceptRichText(False) # 拒绝粘贴富文本仅保留纯文本4. 语法高亮扩展结合QSyntaxHighlighter实现代码 / 日志的语法高亮示例Python 关键字高亮import sys from PySide6.QtGui import QSyntaxHighlighter, QTextCharFormat, QColor from PySide6.QtWidgets import QTextEdit, QApplication class PythonHighlighter(QSyntaxHighlighter): def __init__(self, parentNone): super().__init__(parent) # 定义高亮格式 keyword_format QTextCharFormat() keyword_format.setForeground(QColor(#FF7F00)) # 橙色 keyword_format.setFontWeight(75) # 加粗 # Python 关键字列表 self.keywords [ and, as, assert, break, class, continue, def, del, elif, else, except, False, finally, for, from, global, if, import, in, is, lambda, None, nonlocal, not, or, pass, raise, return, True, try, while, with, yield ] # 存储高亮规则正则表达式 格式 self.highlight_rules [] for keyword in self.keywords: pattern rf\b{keyword}\b # 单词边界匹配 self.highlight_rules.append((pattern, keyword_format)) def highlightBlock(self, text): 对每一行文本应用高亮规则 for pattern, format in self.highlight_rules: import re for match in re.finditer(pattern, text): start, end match.span() self.setFormat(start, end - start, format) class myTextEdit(QTextEdit): def __init__(self, parentNone): super().__init__(parent) self.setupUI() def setupUI(self): self.highlighter PythonHighlighter(self.document()) if __name__ __main__: app QApplication(sys.argv) text_edit myTextEdit() text_edit.show() sys.exit(app.exec())常见场景示例1. 日志输出窗口自动滚动 只读class LogWindow(QMainWindow): def __init__(self): super().__init__() self.text_edit QPlainTextEdit() self.text_edit.setReadOnly(True) self.text_edit.setLineWrapMode(QPlainTextEdit.NoWrap) self.setCentralWidget(self.text_edit) def append_log(self, log_text): 追加日志并自动滚动到末尾 self.text_edit.appendPlainText(log_text) # 自动滚动 scroll_bar self.text_edit.verticalScrollBar() scroll_bar.setValue(scroll_bar.maximum()) # 使用 log_window LogWindow() log_window.append_log([INFO] 程序启动成功) log_window.append_log([ERROR] 数据库连接失败)2. 带行号的代码编辑器简化版import sys from PySide6.QtGui import QPainter, QColor from PySide6.QtWidgets import QWidget, QTextEdit, QHBoxLayout, QPlainTextEdit, QApplication from PySide6.QtCore import Qt class LineNumberWidget(QWidget): 行号显示控件 def __init__(self, text_edit, parentNone): super().__init__(parent) self.text_edit text_edit self.text_edit.cursorPositionChanged.connect(self.update) def paintEvent(self, event): painter QPainter(self) painter.fillRect(event.rect(), QColor(#F0F0F0)) # 行号背景色 # 获取可见的行范围 block self.text_edit.firstVisibleBlock() block_number block.blockNumber() top self.text_edit.blockBoundingGeometry(block).translated(self.text_edit.contentOffset()).top() bottom top self.text_edit.blockBoundingRect(block).height() # 绘制行号 while block.isValid() and top event.rect().bottom(): if block.isVisible() and bottom event.rect().top(): number str(block_number 1) painter.drawText(0, int(top), self.width() - 5, self.text_edit.fontMetrics().height(), Qt.AlignRight, number) block block.next() top bottom bottom top self.text_edit.blockBoundingRect(block).height() block_number 1 # 组合行号和编辑区 class CodeEditor(QWidget): def __init__(self): super().__init__() layout QHBoxLayout(self) layout.setSpacing(0) layout.setContentsMargins(0, 0, 0, 0) self.text_edit QPlainTextEdit() self.line_number LineNumberWidget(self.text_edit) self.line_number.setFixedWidth(40) # 行号宽度 layout.addWidget(self.line_number) layout.addWidget(self.text_edit) if __name__ __main__: app QApplication(sys.argv) editor CodeEditor() editor.show() sys.exit(app.exec())注意事项性能优化处理超大型文本如 10 万行以上时建议关闭实时更新如textChanged信号批量操作后再刷新编码问题读取 / 保存文本时需指定编码如 UTF-8避免乱码与 QTextEdit 区分QTextEdit 支持富文本但性能低QPlainTextEdit 仅纯文本适合大文本场景撤销 / 重做默认开启可通过setUndoRedoEnabled(False)禁用避免内存占用过高换行符兼容不同系统换行符\n/\r\n可通过document().setPlainText()自动适配。总结QPlainTextEdit 是 PySide6 中处理纯文本的核心控件通过基础文本操作、光标控制、信号响应可满足大部分纯文本编辑需求结合语法高亮、行号控件等扩展可实现代码编辑器、日志查看器等复杂功能。重点掌握其轻量级特性、行级操作和信号槽机制即可灵活应用于各类文本处理场景。3. QTextEdit多行文本框QTextEdit是 PySide6 中功能强大的多行富文本编辑控件支持纯文本、HTML 富文本的输入 / 显示还提供文本格式化、撤销 / 重做、查找替换等高级功能是实现记事本、富文本编辑器、聊天框、文档预览等场景的核心组件。核心作用多行富文本 / 纯文本输入如备注、编辑器。核心特性双模式支持可作为纯文本编辑器类似QPlainTextEdit或富文本编辑器支持字体、颜色、段落格式内容操作支持文本插入、删除、替换以及撤销 / 重做、复制 / 粘贴格式控制可设置选中文本的字体、颜色、对齐方式、列表样式等布局与滚动自动换行、水平 / 垂直滚动支持自定义页边距信号反馈文本变化、光标移动、选择范围变更等信号满足交互需求只读模式可切换为只读用于富文本内容展示如帮助文档。基础用法基本初始化与布局import sys from PySide6.QtWidgets import ( QApplication, QWidget, QTextEdit, QVBoxLayout, QPushButton, QHBoxLayout ) from PySide6.QtGui import QFont, QColor from PySide6.QtCore import Qt class TextEditDemo(QWidget): def __init__(self): super().__init__() self.init_ui() def init_ui(self): self.setWindowTitle(QTextEdit 详解) self.resize(800, 600) # 1. 创建核心控件 self.text_edit QTextEdit() # 2. 基础配置 self.text_edit.setPlaceholderText(请输入内容支持富文本) # 占位提示 self.text_edit.setFont(QFont(Microsoft YaHei, 12)) # 默认字体 self.text_edit.setLineWrapMode(QTextEdit.WidgetWidth) # 按控件宽度自动换行 self.text_edit.setTabStopDistance(40) # Tab 缩进距离像素 # 3. 功能按钮布局 btn_layout QHBoxLayout() # 纯文本/富文本切换 self.btn_plain QPushButton(纯文本模式) self.btn_plain.clicked.connect(self.switch_plain_mode) # 设置选中文本颜色 btn_color QPushButton(选中文本设为红色) btn_color.clicked.connect(self.set_text_color) # 插入图片 btn_image QPushButton(插入图片) btn_image.clicked.connect(self.insert_image) # 清空内容 btn_clear QPushButton(清空) btn_clear.clicked.connect(self.text_edit.clear) btn_layout.addWidget(self.btn_plain) btn_layout.addWidget(btn_color) btn_layout.addWidget(btn_image) btn_layout.addWidget(btn_clear) # 4. 主布局 main_layout QVBoxLayout() main_layout.addLayout(btn_layout) main_layout.addWidget(self.text_edit) self.setLayout(main_layout) # 5. 绑定信号监听文本变化 self.text_edit.textChanged.connect(self.on_text_changed) def switch_plain_mode(self): 切换纯文本/富文本模式 if self.text_edit.acceptRichText(): self.text_edit.setAcceptRichText(False) # 禁用富文本纯文本模式 self.btn_plain.setText(富文本模式) else: self.text_edit.setAcceptRichText(True) # 启用富文本 self.btn_plain.setText(纯文本模式) def set_text_color(self): 设置选中文本颜色为红色 # 获取文本光标操作选中文本的核心 cursor self.text_edit.textCursor() if cursor.hasSelection(): # 有选中内容 # 设置选中文本格式 char_format cursor.charFormat() char_format.setForeground(QColor(255, 0, 0)) # 红色 cursor.setCharFormat(char_format) def insert_image(self): 插入图片到光标位置 # 替换为本地图片路径支持 PNG/JPG 等 img_path demo.png # 插入图片参数图片路径、替代文本、尺寸 self.text_edit.insertHtml(fimg src{img_path} width200 height150/) def on_text_changed(self): 文本变化时触发实时统计字符数 # 获取纯文本内容排除富文本标签 plain_text self.text_edit.toPlainText() char_count len(plain_text) self.setWindowTitle(fQTextEdit 详解 - 字符数{char_count}) if __name__ __main__: app QApplication(sys.argv) demo TextEditDemo() demo.show() sys.exit(app.exec())核心功能与 API 详解1. 内容操作文本 / 富文本方法说明示例setPlainText(text)设置纯文本内容覆盖原有内容text_edit.setPlainText(Hello World)toPlainText()获取纯文本内容忽略富文本格式text text_edit.toPlainText()setHtml(html)设置富文本内容HTML 格式text_edit.setHtml(h1标题/h1p段落/p)toHtml()获取富文本的 HTML 源码html text_edit.toHtml()insertPlainText(text)在光标位置插入纯文本text_edit.insertPlainText(插入内容)insertHtml(html)在光标位置插入富文本text_edit.insertHtml(b加粗/b)append(text)追加文本自动换行支持富文本text_edit.append(新的一行)clear()清空所有内容text_edit.clear()undo()/redo()撤销 / 重做操作text_edit.undo()copy()/cut()/paste()复制 / 剪切 / 粘贴text_edit.copy()2. 格式控制选中文本 / 全局1字符格式字体、颜色、样式from PySide6.QtWidgets import QApplication, QMainWindow, QTextEdit from PySide6.QtGui import QFont, QColor, QTextCursor import sys class MainWindow(QMainWindow): def __init__(self): super().__init__() self.init_ui() def init_ui(self): self.setWindowTitle(富文本编辑器) self.resize(800, 600) # 设置窗口大小避免控件太小看不到效果 # 1. 创建核心控件 self.text_edit QTextEdit() # 2. 基础配置 self.text_edit.setPlaceholderText(请输入内容支持富文本) self.text_edit.setLineWrapMode(QTextEdit.LineWrapMode.WidgetWidth) self.text_edit.setTabStopDistance(40) self.text_edit.setAcceptRichText(True) # 3. 设置默认字符格式 # 方式1直接给 QTextEdit 设置默认格式推荐对所有新输入文本生效 # default_format self.text_edit.currentCharFormat() # 获取控件默认格式 # default_format.setFont(QFont(Microsoft YaHei UI, 36, QFont.Weight.Bold)) # 字体 # default_format.setForeground(QColor(#ff0000)) # 字体颜色 # default_format.setBackground(QColor(#EEEE00)) # 背景色 # self.text_edit.setCurrentCharFormat(default_format) # 应用到控件 # 可选方式2通过光标设置后将光标放回控件 cursor self.text_edit.textCursor() char_format cursor.charFormat() char_format.setFont(QFont(Microsoft YaHei UI, 36, QFont.Weight.Bold)) char_format.setForeground(QColor(#ff0000)) char_format.setBackground(QColor(#EEEEaa)) cursor.setCharFormat(char_format) self.text_edit.setTextCursor(cursor) # 关键将修改后的光标放回控件 # 4. 将控件设置为主窗口中心部件必须否则控件不显示 self.setCentralWidget(self.text_edit) if __name__ __main__: app QApplication(sys.argv) window MainWindow() window.show() sys.exit(app.exec())2段落格式对齐、缩进、行距通过QTextBlockFormat控制段落样式from PySide6.QtCore import Qt from PySide6.QtWidgets import QApplication, QMainWindow, QTextEdit from PySide6.QtGui import QFont, QColor, QTextCursor, QTextBlockFormat import sys class MainWindow(QMainWindow): def __init__(self): super().__init__() self.init_ui() def init_ui(self): self.setWindowTitle(富文本编辑器) self.resize(800, 600) # 设置窗口大小避免控件太小看不到效果 # 1. 创建核心控件 self.text_edit QTextEdit() # 2. 基础配置 self.text_edit.setPlaceholderText(请输入内容支持富文本) self.text_edit.setLineWrapMode(QTextEdit.LineWrapMode.WidgetWidth) self.text_edit.setTabStopDistance(40) self.text_edit.setAcceptRichText(True) # 1. 创建段落格式对象 block_format QTextBlockFormat() block_format.setAlignment(Qt.AlignCenter) # 居中对齐 block_format.setLeftMargin(20) # 左缩进 block_format.setLineHeight(200.0, QTextBlockFormat.ProportionalHeight.value) # 行距150% # 2. 应用到当前段落 cursor self.text_edit.textCursor() cursor.setBlockFormat(block_format) # 4. 将控件设置为主窗口中心部件必须否则控件不显示 self.setCentralWidget(self.text_edit) if __name__ __main__: app QApplication(sys.argv) window MainWindow() window.show() sys.exit(app.exec())3列表样式有序 / 无序列表import sys from PySide6.QtWidgets import QApplication, QMainWindow, QTextEdit from PySide6.QtGui import QTextCursor, QTextListFormat class MainWindow(QMainWindow): def __init__(self): super().__init__() self.init_ui() def init_ui(self): self.text_edit QTextEdit(self) self.setCentralWidget(self.text_edit) # 获取当前文本光标 cursor self.text_edit.textCursor() # 设置列表模式 list_format QTextListFormat() # list_format.setStyle(QTextListFormat.ListDecimal) # 设置列表样式为有序数字列表或者 list_format.setStyle(QTextListFormat.ListDisc) # 设置列表样式为无序圆点列表 cursor.createList(list_format) if __name__ __main__: app QApplication([]) window MainWindow() window.show() sys.exit(app.exec())4 光标与选择操作QTextCursor是操作QTextEdit内容的核心工具用于定位光标、选择文本、修改格式import sys from PySide6.QtWidgets import QApplication, QMainWindow, QTextEdit from PySide6.QtGui import QTextCursor, QTextListFormat class MainWindow(QMainWindow): def __init__(self): super().__init__() self.init_ui() def init_ui(self): self.text_edit QTextEdit(self) self.setCentralWidget(self.text_edit) self.text_edit.setText(0123456789abcdefg) # 获取当前文本光标 # 1. 获取当前光标 cursor self.text_edit.textCursor() # 2. 光标定位 cursor.movePosition(QTextCursor.Start) # 移到文本开头End/NextLine/PreviousWord 等 cursor.setPosition(10) # 移到第10个字符位置 # 3. 选择文本从位置5到位置15 cursor.setPosition(5) cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor, 10) # 4. 判断是否有选中内容 if cursor.hasSelection(): selected_text cursor.selectedText() # 获取选中的文本 print(f选中内容{selected_text}) # 5. 替换选中内容 cursor.insertText(替换后的内容) if __name__ __main__: app QApplication([]) window MainWindow() window.show() sys.exit(app.exec())3. 布局与显示配置方法说明可选值setLineWrapMode(mode)自动换行模式QTextEdit.NoWrap不换行、QTextEdit.WidgetWidth按控件宽度、QTextEdit.FixedPixelWidth固定像素宽度setWordWrapMode(mode)单词换行规则QTextOption.WrapAnywhere任意位置换行、QTextOption.WrapAtWordBoundaryOrAnywhere单词边界优先setReadOnly(bool)只读模式仅显示不可编辑True/FalsesetContentsMargins(left, top, right, bottom)内容页边距text_edit.setContentsMargins(10, 10, 10, 10)setVerticalScrollBarPolicy(policy)垂直滚动条策略Qt.ScrollBarAlwaysOn/Qt.ScrollBarAsNeeded/Qt.ScrollBarAlwaysOff4. 常用信号信号触发场景textChanged()文本内容发生任何变化插入 / 删除 / 格式修改cursorPositionChanged()光标位置移动或选择范围变更selectionChanged()选中的文本范围变更editingFinished()编辑完成失去焦点 / 回车copyAvailable(bool)可复制内容状态变化True 有可复制内容典型应用场景1. 简单富文本编辑器import sys from PySide6.QtGui import QFont from PySide6.QtWidgets import QApplication, QMainWindow, QTextEdit class MainWindow(QMainWindow): def __init__(self): super().__init__() self.init_ui() def init_ui(self): self.text_edit QTextEdit(self) self.setCentralWidget(self.text_edit) # 获取当前文本光标 # 1. 获取当前光标和字符格式 self.cursor self.text_edit.textCursor() self.char_format self.cursor.charFormat() # 2. 设置字体加粗 if not self.char_format.font().bold(): self.char_format.setFontWeight(QFont.Bold) self.cursor.setCharFormat(self.char_format) self.text_edit.setTextCursor(self.cursor) print(self.char_format.font().bold()) # 3. 设置斜体 if not self.char_format.font().italic(): self.char_format.setFontItalic(True) self.cursor.setCharFormat(self.char_format) self.text_edit.setTextCursor(self.cursor) print(self.char_format.font().italic()) # 4. 设置下划线 if not self.char_format.font().underline(): self.char_format.setFontUnderline(True) self.cursor.setCharFormat(self.char_format) self.text_edit.setTextCursor(self.cursor) print(self.char_format.font().underline()) if __name__ __main__: app QApplication([]) window MainWindow() window.show() sys.exit(app.exec())2. 聊天消息框只读 富文本展示import sys from PySide6.QtGui import QFont, QTextCursor from PySide6.QtWidgets import QApplication, QMainWindow, QTextEdit class MainWindow(QMainWindow): def __init__(self): super().__init__() self.init_ui() def init_ui(self): self.text_edit QTextEdit(self) self.setCentralWidget(self.text_edit) # 获取当前文本光标 # 1. 获取当前光标和字符格式 self.cursor self.text_edit.textCursor() self.char_format self.cursor.charFormat() # 示例展示带头像和昵称的聊天消息 def add_chat_msg(nickname, content, avatar_path, text_edit): # 构造富文本消息 html f div stylemargin: 5px 0; img src{avatar_path} width30 height30 styleborder-radius: 50%; vertical-align: middle;/ span stylefont-weight: bold; margin: 0 5px;{nickname}/span span{content}/span /div text_edit.append(html) # 自动滚动到底部 text_edit.moveCursor(QTextCursor.End) if __name__ __main__: app QApplication([]) window MainWindow() nickname 拯救地球的怪兽 content 你好世界 avatar_path avatar.png text_edit window.text_edit add_chat_msg(nickname, content, avatar_path, text_edit) window.show() sys.exit(app.exec())3. 文本查找与替换from PySide6.QtGui import QTextDocument # 查找文本 def find_text(text): # 从当前光标位置查找 found text_edit.find(text, QTextDocument.FindWholeWords) # 匹配整词 if not found: # 未找到则回到开头重新查找 text_edit.moveCursor(QTextCursor.Start) found text_edit.find(text) return found # 替换选中的文本 def replace_text(old_text, new_text): if find_text(old_text): cursor text_edit.textCursor() cursor.insertText(new_text)4. 样式定制StyleSheet通过 CSS 样式表自定义QTextEdit外观text_edit.setStyleSheet( QTextEdit { border: 1px solid #CCCCCC; /* 边框 */ border-radius: 6px; /* 圆角 */ padding: 8px; /* 内边距 */ background-color: #FFFFFF; /* 背景色 */ color: #333333; /* 文本颜色 */ font-size: 12px; } QTextEdit:focus { border-color: #0066CC; /* 聚焦时边框变色 */ outline: none; /* 去除默认聚焦外框 */ } QTextEdit:read-only { background-color: #F5F5F5; /* 只读模式背景色 */ color: #666666; } )与 QPlainTextEdit 的区别特性QTextEditQPlainTextEdit核心定位富文本编辑支持 HTML、图片、格式纯文本编辑轻量、高性能性能大量纯文本时性能较低适合大文本如日志、代码格式支持字符 / 段落 / 列表 / 图片 / 表格仅基础文本无富文本适用场景富文本编辑器、聊天框、文档预览代码编辑器、日志查看器最佳实践性能优化处理大文本10 万 字符时优先用QPlainTextEdit批量修改文本时先调用text_edit.blockSignals(True)关闭信号修改后恢复避免频繁触发textChanged。富文本兼容性自定义富文本时尽量使用标准 HTML 标签b/i/img等避免兼容问题读取富文本时优先用toHtml()写入时用setHtml()保证格式完整。用户体验只读模式下设置setCursor(Qt.IBeamCursor)保持光标样式一致长文本场景添加 “自动滚动到底部” 选项提升阅读体验。资源管理插入的图片若为本地文件需保证路径有效也可将图片嵌入 HTMLbase64 编码避 免路径依赖。