文本编辑框QTextEdit

继承  QObject-->QWidget-->QFrame-->QAbstractScrollArea-->QTextEdit

QTextEdit类是一个多行文本框控件,可以显示多行文本内容,当文本内容超出控件显示范围时,可以显示水平个垂直滚动条,Qtextedit不仅可以用来显示文本还可以用来显示HTML4文档,图像,表格

任何一个文本编辑器的程序都要用到QTextEdit作为输入文本的容器,在它里面输入的可编辑文本由QTextDocument作为载体

文本:


import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit
from PyQt5.QtGui import QTextCharFormat

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,300)
        t = QTextEdit('我爱学习', self)   #创建多行文本对象
        #参数1  显示的文本
        #参数2  父控件
        #注意  光标在0位置
        t.setPlaceholderText('占位提示')   #在文本框内部内容为空时, 给用户的文本提示信息
        s=t.placeholderText()   #返回占位提示信息

        t.setPlainText('我爱我的祖国') #设置普通文本,原来的文本被覆盖掉
        #注意  光标在0位置
        t.insertPlainText(',我想为祖国做点贡献')   #在光标处插入普通文本
        #会自动移动光标
        s=t.toPlainText() #返回文本框的文本内容-纯文本

        t.setHtml('<h1>我爱我的祖国</h1>')  #设置HTML文本-富文本,原来的文本被覆盖掉
        # 注意  光标在0位置
        t.insertHtml('<h1>,我想为祖国做点贡献</h1>') #在光标处插入HTML文本-富文本
        # 会自动移动光标
        s=t.toHtml() #返回文本框的文本内容-富文本

        t.setText('<h1>我爱我的祖国</h1>') #设置文本-自动判断是普通文本还是富文本
        # 注意  光标在0位置     原来的文本被覆盖掉
        #t.append(',我想为祖国做点贡献')  #在尾部追加文本-自动采用前面的文本格式,自动判断是普通文本还是富文本
        #t.clear()  #清空文本

        tc=t.textCursor()  #获取文本光标对象->QTextCursor

        #利用文本光标对象插入文本-格式一
        tc.insertText('中国人')  #在光标处插入文本,自动判断格式
        #自动移动光标

        # 利用文本光标对象插入文本-格式二-带字体
        tcf=QTextCharFormat()  #创建文本字符格式对象
        tcf.setToolTip('楷体')  #当鼠标在这个字体上悬停时的提示信息
        tcf.setFontFamily('李明')  #设置字体
        tcf.setFontPointSize(30)  #设置字体大小
        tc.insertText('天津',tcf)
        #参数2  可选-字体

        # 利用文本光标对象插入HTML文本
        tc.insertHtml('<h3>塘沽</h3>')
        # 自动移动光标



        #print(s)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())



利用文本光标对象插入图片:

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit,QPushButton
from PyQt5.QtGui import QTextCharFormat,QTextImageFormat,QTextFrameFormat

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,300)
        t = QTextEdit('我爱学习', self)
        t.setText('<h1>我爱我的祖国</h1>')
        tb=QPushButton('按钮',self)
        tb.move(100,200)

        def A():
            tc = t.textCursor()  # 获取文本光标对象->QTextCursor

            # 利用文本光标对象插入图片
            tif = QTextImageFormat()  # 创建文本图像格式
            tif.setName('大象.png')  # 设置图片
            tif.setWidth(100)  # 设置图片宽度
            tif.setHeight(100)  # 设置图片高度
            tc.insertImage(tif,QTextFrameFormat.InFlow)  #插入图片-非环绕
            #参数2 图片位置
            #QTextFrameFormat.FloatRight=2   在右边
            #QTextFrameFormat.FloatLeft=1    在左边
            #QTextFrameFormat.InFlow=0      在光标处
        tb.clicked.connect(A)





        #print(s)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())

利用文本光标对象插入文本片段:

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit,QPushButton
from PyQt5.QtGui import QTextDocumentFragment

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,300)
        t = QTextEdit('我爱学习', self)
        tb=QPushButton('按钮',self)
        tb.move(100,200)

        def A():
            tc = t.textCursor()  # 获取文本光标对象->QTextCursor

            # 利用文本光标对象插入文本片段
            #tdf=QTextDocumentFragment.fromHtml('<h2>我是中国人</h2>')  #创建富文本片段
            tdf = QTextDocumentFragment.fromPlainText('<h2>我是中国人</h2>')  # 创建普通文本片段
            tc.insertFragment(tdf)  #在光标处插入文本片段
            #自动移动光标
            t.setFocus()

        tb.clicked.connect(A)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())

 列表-word的项目编号和项目符号:

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit,QPushButton
from PyQt5.QtGui import QTextListFormat

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,300)
        t = QTextEdit('我爱学习', self)
        tb=QPushButton('按钮',self)
        tb.move(100,200)

        def A():
            tc = t.textCursor()  # 获取文本光标对象->QTextCursor

            # 利用文本光标对象插入列表-个人理解:word的段落编号和项目符号

            #方式一
            #s=tc.insertList(QTextListFormat.ListDecimal) #在当前光标处插入一个新块,并使其成为具有给定格式的新创建列表的第一个列表项。返回创建的列表
            #返回值类型QTextList
            #QTextListFormat.ListCircle   一个空的圆圈
            #QTextListFormat.ListDisc     一个圆圈
            #QTextListFormat.ListSquare   一个方块
            #QTextListFormat.ListDecimal    十进制值按升序排列
            #QTextListFormat.ListLowerAlpha 小写拉丁字符按字母顺序排列
            #QTextListFormat.ListUpperAlpha 大写拉丁字符按字母顺序排列
            #QTextListFormat.ListLowerRoman   小写罗马数字(仅支持最多4999项)
            #QTextListFormat.ListUpperRoman   大写罗马数字(仅支持最多4999项)


            #方式二
            #tc.createList(QTextListFormat.ListDecimal) #创建并返回具有给定格式的新列表,并使当前段落是第一个列表项

            #方式三
            tlf=QTextListFormat()
            tlf.setIndent(1)  #缩进1个Tab
            tlf.setNumberPrefix('>>') #前缀-放在样式前面
            tlf.setNumberSuffix('<<')  #后缀-放在样式后面
            tlf.setStyle(QTextListFormat.ListDecimal) #设置样式
            #参数  参考方式一
            #只有设置了样式,前缀后缀才有效果
            tc.createList(tlf)
            
            t.setFocus()

        tb.clicked.connect(A)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())
   


 表格:

名称:记录--一行             字段-一列

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit,QPushButton
from PyQt5.QtGui import QTextTableFormat,QTextLength
from PyQt5.QtCore import Qt

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,300)
        t = QTextEdit(self)
        tb=QPushButton('按钮',self)
        tb.move(100,200)

        def A():
            tc = t.textCursor()  # 获取文本光标对象->QTextCursor

            # 利用文本光标对象插入表格
            #tt=tc.insertTable(3,2 )  #在光标处插入3行2列的表格-不带格式
            #返回值类型   QTextTable
            #表格不环绕单独占用行

            ttf=QTextTableFormat()  #创建表格格式
            ttf.setAlignment(Qt.AlignRight)     #设置对齐方式
            ttf.setCellPadding(1)           #设置内边距
            ttf.setCellSpacing(1)    #设置外边距
            ttf.setColumnWidthConstraints((QTextLength(QTextLength.PercentageLength, 50),QTextLength(QTextLength.PercentageLength, 40)))  # 列宽限制
            # 元组
            #按百分比计算
            tt = tc.insertTable(3, 2,ttf)   #在光标处插入3行2列的表格-带格式
            # 返回值类型   QTextTable
            # 表格不环绕单独占用行
            tt.appendColumns(2)  #追加两列
            tt.appendRows(1)   #追加1行
            
            t.setFocus()

        tb.clicked.connect(A)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())

表格还有很多内容不会:如何操作表格 ??

插入文本块-段落:

段落是以回车换行符为间隔的

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit,QPushButton
from PyQt5.QtGui import QTextBlockFormat,QTextCharFormat,QColor
from PyQt5.QtCore import Qt

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,300)
        t = QTextEdit(self)
        tb=QPushButton('按钮',self)
        tb.move(100,200)
        t.setText('我爱祖国')

        def A():
            tc = t.textCursor()  # 获取文本光标对象->QTextCursor

            # 利用文本光标对象插入文本块-段落

            #tc.insertBlock()    #插入文本块-插入段落-在光标处插入回车换行
            tbf=QTextBlockFormat()   #创建文本块格式对象
            #这种格式是段落级别的
            tbf.setAlignment(Qt.AlignLeft)  #设置段落对齐方式
            # Qt.AlignRight   水平靠右
            # Qt.AlignLeft    水平靠左
            # Qt.AlignHCenter   居中
            # Qt.AlignJustify
            # Qt.AlignTop   垂直顶部
            # Qt.AlignBottom   垂直底部
            # Qt.AlignVCenter   垂直居中
            # Qt.AlignBaseline
            # Qt.AlignCenter=Qt.AlignHCenter | Qt.AlignVCenter

            tbf.setRightMargin(20)   #设置边距-文本离右边的距离
            #单位  像素
            tbf.setLeftMargin(20)  #设置边距-文本离左边的距离
            tbf.setBottomMargin(20)  #设置边距-文本离底边的距离
            tbf.setTopMargin(20)  #设置边距-文本离顶部的距离

            tbf.setIndent(1)  #缩进1个Tab

            tcf=QTextCharFormat()  #创建文本字符格式对象
            #这个格式是字符级别的
            tcf.setFontFamily('隶书')  #设置字体
            s=tcf.font()  #返回字体对象
            s1=s.family()  #返回字体名称-隶书
            s1=s.style() #返回字体样式-int
            s1=s.bold()  #返回是否加粗
            tcf.setFontItalic(True)  #是否倾斜
            tcf.setFontPointSize(30)  #字体大小
            #fontPointSize()   返回字体大小
            #tcf.setFontOverline(True)  #是否有上划线
            #fontOverline()  返回是否有上划线

            #tcf.setFontStrikeOut(True) #设置删除线
            #s1=tcf.fontStrikeOut()  #返回是否有删除线

            tcf.setFontUnderline(True)  #设置下划线
            #s1=tcf.fontUnderline()  #返回是否具有下划线
            tcf.setUnderlineColor(QColor(255,25,200,10)) #设置下划线颜色
            #参数4 alpha没有效果啊??
            s=tcf.underlineColor()  #返回下划线的颜色对象-QColor
            print(s.red())  #返回QColor对象中的red值
            print(s.green())  # 返回QColor对象中的green值
            print(s.blue())  # 返回QColor对象中的blue值
            print(s.alpha())  # 返回QColor对象中的alpha值


            #fontWeight
            #tcf.setFontWeight(500)  #设置字体粗细
            #s1=tcf.fontWeight()  #返回字体粗细

            #fontWordSpacing
            #tcf.setFontWordSpacing(10)  #设置单词间距
            #s1=tcf.fontWordSpacing()  #返回单词间距-float

            #tcf.setFontLetterSpacing(200)  #设置字母间距
            #s = tcf.fontLetterSpacingType()  #返回字母间距类型
            #s1=tcf.fontLetterSpacing()  #返回字母间距-float


            #tc.insertBlock(tbf)  # 插入文本块(带格式)
            tc.insertBlock(tbf,tcf)  # 插入文本块(带格式)
            #在文本中间插入tcf好像没有效果
            t.setFocus()


            print(s1)

        tb.clicked.connect(A)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())

 框架:

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit,QPushButton
from PyQt5.QtGui import QTextFrameFormat,QColor

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,300)
        t = QTextEdit(self)
        tb=QPushButton('按钮',self)
        tb.move(100,200)
        t.setText('我爱祖国')

        def A():
            tc = t.textCursor()  # 获取文本光标对象->QTextCursor

            # 利用文本光标对象插入文本框架
            tff=QTextFrameFormat()  #创建文本框架对象
            tff.setBorder(10)   #设置边框的宽度,单位:像素
            tff.setBorderBrush(QColor(255,0,0))  #设置框架下边框和右边框的颜色
            tff.setRightMargin(10)  #文本框架离右边的间距
            tc.insertFrame(tff) #插入文本框架
            #返回值类型  QTextFrame

            doc=t.document()  #获取文本框的文档
            root_frame=doc.rootFrame()  #获取文档的根框架
            root_frame.setFrameFormat(tff)  #给框架设置格式
            
        tb.clicked.connect(A)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())

格式设置和合并: 

 设置块字符格式:

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit,QPushButton
from PyQt5.QtGui import QTextFrameFormat,QColor,QTextCharFormat

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,300)
        t = QTextEdit(self)
        tb=QPushButton('按钮',self)
        tb.move(100,200)
        t.setText('我爱祖国')

        def A():
            tc = t.textCursor()  # 获取文本光标对象->QTextCursor

            
            tcf=QTextCharFormat()
            tcf.setFontFamily('幼圆')
            tcf.setFontPointSize(30)
            tcf.setFontUnderline(True)
            tc.setBlockCharFormat(tcf)  #设置当前块(或选择中包含的所有块)的块char格式-【设置当前段落的字符格式】
            #光标在文本中间好像不行
            
        tb.clicked.connect(A)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())

设置块格式[段落格式]:

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit,QPushButton
from PyQt5.QtGui import QTextBlockFormat
from PyQt5.QtCore import Qt

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,300)
        t = QTextEdit(self)
        tb=QPushButton('按钮',self)
        tb.move(100,200)
        t.setText('我爱祖国')

        def A():
            tc = t.textCursor()  # 获取文本光标对象->QTextCursor

            tbf=QTextBlockFormat()
            tbf.setAlignment(Qt.AlignCenter)
            tc.setBlockFormat(tbf)  #设置当前块的块格式(或选择中包含的所有块)以进行格式化
            #设置当前段落格式(或选择中包含的所有段落)

            t.setFocus()

        tb.clicked.connect(A)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())

设置当前(选中)字符格式:

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit,QPushButton
from PyQt5.QtGui import QTextCharFormat

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,300)
        t = QTextEdit(self)
        tb=QPushButton('按钮',self)
        tb.move(100,200)
        t.setText('我爱祖国')

        def A():
            tc = t.textCursor()  # 获取文本光标对象->QTextCursor

            tcf=QTextCharFormat()
            tcf.setFontFamily('幼圆')
            tcf.setFontPointSize(30)
            tcf.setFontUnderline(True)
            tc.setCharFormat(tcf)  #将光标的当前字符格式设置为给定格式。如果光标有选择,则给定格式应用于当前选择

            t.setFocus()

        tb.clicked.connect(A)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())

合并格式: 


import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit,QPushButton
from PyQt5.QtGui import QTextCharFormat

class Demo(QWidget):
def __init__(self):
super().__init__()
self.resize(300,300)
t = QTextEdit(self)
tb=QPushButton('按钮',self)
tb.move(100,200)
t.setText('我爱祖国')

def A():
tc = t.textCursor() # 获取文本光标对象->QTextCursor

tcf=QTextCharFormat()
tcf.setFontFamily('幼圆')
tcf.setFontPointSize(30)
tcf.setFontUnderline(True) #下划线
tc.setCharFormat(tcf)

tcf1 = QTextCharFormat()
tcf1.setFontStrikeOut(True) #删除线
tc.mergeCharFormat(tcf1) #合并当前字符格式-->在原来字符格式的基础上再加上新格式tcf1

#tc.mergeBlockCharFormat() #合并块字符格式
#tc.mergeBlockFormat() #合并块格式

t.setFocus()

tb.clicked.connect(A)

if __name__ == '__main__':
app = QApplication(sys.argv)
demo = Demo()
demo.show()
sys.exit(app.exec_())
 

获取内容和格式相关: 

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit,QPushButton
from PyQt5.QtGui import QTextCharFormat

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,300)
        t = QTextEdit(self)
        tb=QPushButton('按钮',self)
        tb.move(100,200)
        t.setText('我爱祖国')

        def A():
            tc = t.textCursor()  # 获取文本光标对象->QTextCursor

            tcf=QTextCharFormat()
            tcf.setFontFamily('幼圆')
            tcf.setFontPointSize(30)
            tcf.setFontUnderline(True)
            tc.insertText('天津',tcf)

            s=tc.block()   #获取光标所在的文本块
            #返回值类型 QTextBlock
            print(s.text())  #返回文本框的内容
            #天津我爱祖国
            print(s.blockNumber())  #返回段落编号

            #c=currentList() -> QTextList    获取当前所在的文本列表-段落编号或项目编号
            #c.couut()   返回列表的总数

            #blockFormat() -> QTextBlockFormat   获取光标所在的文本块格式
            #blockCharFormat() -> QTextCharFormat   获取光标所在的文本块字符格式
            #charFormat() -> QTextCharFormat    获取文本字符格式
            #currentFrame() -> QTextFrame   获取当前所在的框架
            #currentTable() -> QTextTable    获取当前的表格




            t.setFocus()

        tb.clicked.connect(A)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())

利用文本光标操作光标:

1.设置光标位置

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit,QPushButton
from PyQt5.QtGui import QTextCursor

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,300)
        t = QTextEdit(self)
        tb=QPushButton('按钮',self)
        tb.move(100,200)
        t.setText('我爱祖国我爱中华人民共和国')

        def A():
            tc = t.textCursor()  # 获取文本光标对象->QTextCursor

            tc.setPosition(6, QTextCursor.KeepAnchor)  #设置光标位置
            #参数2  锚点移动模式:
            #QTextCursor.MoveAnchor    将锚点移动到与光标本身相同的位置(默认)
            #QTextCursor.KeepAnchor    将锚固定在原处
            #说明:锚点与光标之间的内容会被选中
            t.setTextCursor(tc)  #把文本光标方向设置回去---setPosition才有效果
            
            t.setFocus()

        tb.clicked.connect(A)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())

 2.移动光标:

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit,QPushButton
from PyQt5.QtGui import QTextCursor

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,300)
        t = QTextEdit(self)
        tb=QPushButton('按钮',self)
        tb.move(100,200)
        t.setText('我爱祖国我爱中华人民共和国')

        def A():
            tc = t.textCursor()  # 获取文本光标对象->QTextCursor

            tc.movePosition(QTextCursor.StartOfLine, QTextCursor.MoveAnchor)  #移动光标
            #参数1 移动选项:
            #QTextCursor.NoMove   将光标保持在原位
            #QTextCursor.Start    移至文档的开头
            #QTextCursor.StartOfLine   移动到当前行的开头
            #QTextCursor.StartOfBlock   移动到当前块的开头
            #QTextCursor.StartOfWord   移动到当前单词的开头
            #QTextCursor.PreviousBlock   移动到上一个块的开头
            #QTextCursor.PreviousCharacter  移至上一个字符
            #QTextCursor.PreviousWord   移到上一个单词的开头
            #QTextCursor.Up   向上移动一行
            #QTextCursor.Left   向左移动一个字符
            #QTextCursor.WordLeft   向左移动一个单词
            #QTextCursor.End    移到文档的末尾
            #QTextCursor.EndOfLine  移动到当前行的末尾
            #QTextCursor.EndOfWord   移到当前单词的末尾
            #QTextCursor.EndOfBlock  移动到当前块的末尾
            #QTextCursor.NextBlock    移动到下一个块的开头
            #QTextCursor.NextCharacter   移动到下一个角色
            #QTextCursor.NextWord   转到下一个单词。
            #QTextCursor.Down    向下移动一行。
            #QTextCursor.Right   向右移动一个角色。
            #QTextCursor.WordRight    向右移动一个单词。
            #QTextCursor.NextCell      移动到当前表中下一个表格单元格的开头。如果当前单元格是行中的最后一个单元格,则光标将移动到下一行中的第一个单元格
            #QTextCursor.PreviousCell   移动到当前表内的上一个表格单元格的开头。如果当前单元格是行中的第一个单元格,则光标将移动到上一行中的最后一个单元格
            #QTextCursor.NextRow   移动到当前表中下一行的第一个新单元格。
            #QTextCursor.PreviousRow   移动到当前表中上一行的最后一个单元格。

            #参数2  锚点移动模式:
            #QTextCursor.MoveAnchor    将锚点移动到与光标本身相同的位置(默认)
            #QTextCursor.KeepAnchor    将锚固定在原处
            #说明:锚点与光标之间的内容会被选中
            t.setTextCursor(tc)  #把文本光标方向设置回去---setPosition和movePosition才有效果

            t.setFocus()

        tb.clicked.connect(A)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())

 3.选中:

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit,QPushButton
from PyQt5.QtGui import QTextCursor

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,300)
        t = QTextEdit(self)
        tb=QPushButton('按钮',self)
        tb.move(100,200)
        t.setText('我爱祖国我爱中华人民共和国')

        def A():
            tc = t.textCursor()  # 获取文本光标对象->QTextCursor

            tc.select(QTextCursor.BlockUnderCursor)  #选中
            #参数:
            #QTextCursor.Document    选择整个文档。
            #QTextCursor.BlockUnderCursor  选择光标下的文本块
            #QTextCursor.LineUnderCursor   选择光标下的文本行
            #QTextCursor.WordUnderCursor  选择光标下的单词。如果光标未定位在可选字符串中,则不选择任何文本

            t.setTextCursor(tc)  #把文本光标方向设置回去---setPosition和movePosition和select才有效果

            t.setFocus()

        tb.clicked.connect(A)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())

获取选中的内容: 

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit,QPushButton

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,300)
        t = QTextEdit(self)
        tb=QPushButton('按钮',self)
        tb.move(100,200)
        t.setText('我爱祖国我爱中华人民共和国')
        t.textCursor().insertTable(3, 4)

        def A():
            tc = t.textCursor()  # 获取文本光标对象->QTextCursor

            s=tc.selectedText() #返回选中的内容
            #返回值类型  str

            s=tc.selection() #返回文本片段对象
            #返回值类型 QTextDocumentFragment
            c=s.toPlainText()  #把文本片段转化成普通文本
            c=s.toHtml()  #把文本片段转化成富文本
            c=s.isEmpty()  #是否为空

            c=tc.selectedTableCells()  #获取选中的单元格
            #返回值  (1, 2, 1, 2)  是个元组
            #第一个值:选中单元格的起始行
            #第二个值: 选中的总行数
            #第三个值:选中单元格的起始列
            #第四个值:选中的总列数

            print(c)

            t.setFocus()

        tb.clicked.connect(A)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())

获取选中内容的位置、取消选中、是否有选中、删除选中文本、删除字符 

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit,QPushButton

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,300)
        t = QTextEdit(self)
        tb=QPushButton('按钮',self)
        tb.move(100,200)
        t.setText('我爱祖国我爱中华人民共和国')

        def A():
            tc = t.textCursor()  # 获取文本光标对象->QTextCursor

            print(tc.selectionStart())  #选中文本的光标的起始位置
            print(tc.selectionEnd())    #选中文本的光标的结束位置

            #tc.clearSelection()  #取消文本的选中
            #t.setTextCursor(tc)  #必须方向设置,clearSelection才有效果

            print(tc.hasSelection()) #是否有选中文本
            tc.removeSelectedText()  #移除选中的文本

            #tc.deleteChar()  #如果没有选中文本, 删除文本光标后一个字符;如果有选中文本, 则删除选中文本
            tc.deletePreviousChar()  #如果没有选中文本, 删除文本光标前一个字符;如果有选中文本, 则删除选中文本

            t.setFocus()

        tb.clicked.connect(A)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())

获取、判断光标的位置: 

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit,QPushButton

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,300)
        t = QTextEdit(self)
        tb=QPushButton('按钮',self)
        tb.move(100,200)
        t.setText('我爱祖国我爱中华人民共和国')

        def A():
            tc = t.textCursor()  # 获取文本光标对象->QTextCursor

            #print(tc.atBlockEnd())   #光标是否在文本块末尾
            #print(tc.atBlockStart())  #光标是否在文本块开始
            #print(tc.atEnd())   #光标是否在文档末尾
            #atStart()  是否在文档开始

            #print(tc.columnNumber())  #光标在第几列
            #print(tc.position())   #返回光标位置
            #返回整个文本框中的字符序号

            print(tc.positionInBlock() )  #光标在文本块中的位置--字符序号

            t.setFocus()

        tb.clicked.connect(A)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())

开始和结束编辑标识:

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit,QPushButton

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,300)
        t = QTextEdit(self)
        tb=QPushButton('按钮',self)
        tb.move(100,200)
        t.setText('我爱祖国我爱中华人民共和国')

        def A():
            tc = t.textCursor()  # 获取文本光标对象->QTextCursor

            tc.beginEditBlock()
            tc.insertBlock()
            tc.insertText('123')
            tc.insertBlock()
            tc.insertText('456')
            tc.insertBlock()
            tc.insertText('789')
            tc.endEditBlock()
            #从beginEditBlock()到endEditBlock()之间的操作看做是一个独立的操作


            t.setFocus()

        tb.clicked.connect(A)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())

自动格式化: 

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit,QPushButton

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,300)
        t = QTextEdit(self)
        tb=QPushButton('按钮',self)
        tb.move(100,200)
        t.setText('我爱祖国我爱中华人民共和国')

        def A():
            t.setAutoFormatting(QTextEdit.AutoBulletList)   #设置自动格式化
            #QTextEdit.AutoNone    不要做任何自动格式化---默认值
            #QTextEdit.AutoBulletList   自动创建项目符号列表(例如,当用户在最左侧列中输入星号('*')时,或在现有列表项中按Enter键
            #QTextEdit.AutoAll   应用所有自动格式。目前仅支持自动项目符号列表。


            t.setFocus()

        tb.clicked.connect(A)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())

 软换行模式:--文本内容超过一行时如何处理

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit,QPushButton
from PyQt5.QtGui import QTextOption

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,300)
        t = QTextEdit(self)
        tb=QPushButton('按钮',self)
        tb.move(100,200)
        t.setText('我爱祖国我爱中华人民共和国')

        def A():
            t.setLineWrapMode(QTextEdit.FixedColumnWidth)  #设置软换行模式
            #QTextEdit.NoWrap  没有软换行, 超过宽度后, 会产生水平滚动条
            #QTextEdit.WidgetWidth   以控件的宽度为限制,但会保持单词的完整性
            #QTextEdit.FixedPixelWidth  填充像素宽度---超过这个像素宽度就软换行,配合setLineWrapColumnOrWidth(int)使用
            #QTextEdit.FixedColumnWidth=3   填充列的宽度--超过这个列数就换行,配合 setLineWrapColumnOrWidth(int)

            s=t.lineWrapMode()   #返回软换行模式--int

            t.setLineWrapColumnOrWidth(10)  #设置像素宽度或列数
            #lineWrapColumnOrWidth() -> int    返回像素宽度或列数

            t.setWordWrapMode(QTextOption.WordWrap)  #设置单词换行模式
            #QTextOption.NoWrap   文本根本没有包装。
            #QTextOption.WordWrap=1    保持单词完整性
            #QTextOption.ManualWrap   与QTextOption.NoWrap相同
            #QTextOption.WrapAnywhere   宽度够了之后, 随意在任何位置换行
            #QTextOption.WrapAtWordBoundaryOrAnywhere   尽可能赶在单词的边界, 否则就在任意位置换行

            s=t.wordWrapMode() #-> QTextOption.WrapMode   获取单词换行模式
            print(s)


            t.setFocus()

        tb.clicked.connect(A)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())

 覆盖或插入:

t.setOverwriteMode(True) #设置是否覆盖模式
s=t.overwriteMode() #覆盖模式返回True,插入模式返回False

 光标宽度:

t.setCursorWidth(int)      设置光标宽度

s=t.cursorWidth()   #返回光标宽度

s=t.cursorRect() #返回光标矩形

#QRect(4, 4, 1, 14) 第3 第4 是光标的宽度和高度

段落对齐方式:

 t.setAlignment(Qt.AlignLeft)      #设置段落对齐方式

 #Qt.AlignLeft    左对齐

#Qt.AlignRight   右对齐

#Qt.AlignCenter   居中对齐

 字体格式:

 s=QFontDialog.getFont()     #打开字体对话框

# 返回值    (<PyQt5.QtGui.QFont object at 0x000000D12B5BE5F8>, False)
#第一个数:字体对象QFont; 第二个数:True 点击的是确定按钮 False 点击的是取消按钮

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit,QPushButton
from PyQt5.QtGui import QFont

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,300)
        t = QTextEdit(self)
        tb=QPushButton('按钮',self)
        tb.move(100,200)
        t.setText('我爱祖国我爱中华人民共和国')

        def A():
            t.setFontFamily('黑体')  #设置字体
            s=t.fontFamily()  #返回字体【黑体】
            t.setFontPointSize(20)  #字体大小
            s=t.fontPointSize()  #返回字体大小
            #20.0
            t.setFontWeight(QFont.Thin)   #设置字体粗细
            #枚举值  从小到大:QFont.Thin=0   QFont.ExtraLight    QFont.Light
            #QFont.Normal    QFont.Medium     QFont.DemiBold
            #QFont.Bold   QFont.ExtraBold     QFont.Black
            s=t.fontWeight()  #返回字体粗细
            t.setFontItalic(True)   #设置是否斜体
            s=t.fontItalic()   #返回是否斜体
            t.setFontUnderline(True)  #设置是否下划线
            s=t.fontUnderline()  #返回是下划线

            font=QFont()  #创建字体实例
            font.setStrikeOut(True)  #删除线
            t.setCurrentFont(font)  #统一设置字体格式

            print(s)
            t.setFocus()

        tb.clicked.connect(A)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())

颜色设置:

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit,QPushButton
from PyQt5.QtGui import QColor

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,300)
        t = QTextEdit(self)
        tb=QPushButton('按钮',self)
        tb.move(100,200)
        t.setText('我爱祖国我爱中华人民共和国')

        def A():
            #t.setTextBackgroundColor(QColor(255,0,0))  #设置文本背景颜色
            #s=t.textBackgroundColor() #返回文本背景颜色对象 QColor
            #<PyQt5.QtGui.QColor object at 0x000000E6A6C9E048>
            t.setTextColor(QColor(255,0,0))  #设置文本颜色
            s=t.textColor() #返回文本颜色对象 QColor
            print(s)
            t.setFocus()

        tb.clicked.connect(A)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())

字符格式和合并:

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit,QPushButton
from PyQt5.QtGui import QColor,QTextCharFormat

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,300)
        t = QTextEdit(self)
        tb=QPushButton('按钮',self)
        tb.move(100,200)
        t.setText('我爱祖国我爱中华人民共和国')

        def A():
            tcf=QTextCharFormat()
            tcf.setFontFamily('幼圆')
            tcf.setFontPointSize(30)

            t.setCurrentCharFormat(tcf)   #给字符设置格式
            tcf.setFontUnderline(True)
            t.mergeCurrentCharFormat(tcf)  #合并当前字符格式-->在原来字符格式的基础上再加上新格式tcf


            t.setFocus()

        tb.clicked.connect(A)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())

大小写格式:

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit,QPushButton
from PyQt5.QtGui import QColor,QTextCharFormat,QFont

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,300)
        t = QTextEdit(self)
        tb=QPushButton('按钮',self)
        tb.move(100,200)
        t.setText('我爱祖国我爱中华人民共和国')

        def A():
            tcf=QTextCharFormat()
            tcf.setFontPointSize(20)
            tcf.setFontCapitalization(QFont.Capitalize)  #设置大小写
            #QFont.MixedCase  这是正常的文本呈现选项,不应用大写更改。
            #QFont.AllUppercase    全大写类型呈现的文本。
            #QFont.AllLowercase   全小写类型呈现的文本。
            #QFont.SmallCaps      以小型大写字母呈现的文本。
            #QFont.Capitalize    每个单词首字母大写

            tcf.setForeground(QColor(255,0,0))  #设置前景色
            t.setCurrentCharFormat(tcf)   #给字符设置格式

            t.setFocus()

        tb.clicked.connect(A)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())

常用编辑操作: 

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit,QPushButton
from PyQt5.QtGui import QTextDocument

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,300)
        t = QTextEdit(self)
        tb=QPushButton('按钮',self)
        tb.move(100,200)
        t.setText('dse abc ABC abcd  AbC 我爱祖国 jhg abc kwd')

        def A():
            #t.copy()   #复制
            #t.paste()  #粘贴
            #print(t.canPaste())  #能否粘贴  返回值 bool
            #t.setUndoRedoEnabled(True)   #???
            #t.redo()  #重做--取消撤销操作
            #t.setUndoRedoEnabled(False)  #禁止撤销和重做
            #t.undo()   #撤销
            #t.selectAll()  #全选
            s=t.find('abc',QTextDocument.FindBackward | QTextDocument.FindCaseSensitively | QTextDocument.FindWholeWords)  #查找
            #找到返回True;没找到返回False
            #QTextDocument.FindBackward   向后搜索而不是向前搜索---默认
            #QTextDocument.FindCaseSensitively  区分大小写;默认是不区分
            #QTextDocument.FindWholeWords  匹配仅完整的单词

            print(s)
            t.setFocus()

        tb.clicked.connect(A)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())

 滚动到锚点:

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QTextEdit,QPushButton
from PyQt5.QtGui import QTextDocument

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(300,300)
        t = QTextEdit(self)
        tb=QPushButton('按钮',self)
        tb.move(100,200)
        t.insertPlainText('dse abc ABC abcd  AbC 我爱祖国
')
        t.insertPlainText('abc'*300)
        t.insertHtml('<a name="lm" href="#锚点内容">百度</a>')  #给指定的文本插入锚点
        #<a name="锚点名称" href="#锚点内容"> 百度 </a>      百度是显示的内容

        def A():
            t.scrollToAnchor('lm')   #滚动到锚点
            #参数 锚点名称
            t.setFocus()

        tb.clicked.connect(A)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())

只读:

t.setReadOnly(True) #只读属性,用户不能编辑-代码可以编辑
s=t.isReadOnly() #返回是否只读

制表符: 

t.setTabChangesFocus(True) #Tab键是改变焦点的功能,没有制表符的功能
#默认是False 是制表符的功能
t.setTabStopDistance(10) #设置制表符的距离-默认80(像素)
#参数 浮点数
#按下Tab键,把光标移到离左边界固定的距离
#setTabStopWidth(p_int) 这个也可以设置
s=t.tabStopDistance() #返回Tab的距离
#返回值 浮点数 10.0
#tabStopWidth() -> int 这个也可以返回

信号:

textChanged()    文本内容发生改变时, 发射的信号

selectionChanged()    选中内容发生改变时, 发射的信号

cursorPositionChanged()    光标位置发生改变时, 发射的信号

currentCharFormatChanged(QTextCharFormat)     当前额字符格式发生改变时, 发射的信号

copyAvailable(bool yes)    复制可用时

redoAvailable(bool available)    重做可用时

undoAvailable(bool available)    撤销可用时

天子骄龙

原文地址:https://www.cnblogs.com/liming19680104/p/10357263.html