GUI學習之十二——QTextEdit學習總結


在學習了QFrame和QAbstractScrollArea兩個父類后,接下來是一個重頭戲:QTextEdit。

一.QTextEdit特性

QTextEdit是一個高級的WYSIWYG(What You See Is What You Get所見即所得)編輯/查看器,支持使用HTML4標簽子集的富文本格式。

QTextEdit它經過優化,可以處理大型文檔並快速響應用戶的輸入,可以加載純文本和富文本文件,用來顯示圖像、列表和表格。

QTextEdit的父類是QAbstractScrollArea,可以通過滾動條調整顯示界面。

 二.功能作用

1.提示占位文本

te.setPlaceholderText('占位文本')      #設定占位文本
te.placeholderText()                  #獲取占位文本

占位文本是控件的固有特性,在不改變的前提下是不會隨着控件內文本的變化而改變的。

2.文本內容設置

由於QTextEdit是支持普通文本和html標簽的,分別有兩種文本的操作

a.普通文本設定

QTextEdit.setPlainText(str)         #普通文本設定
QTextEdit.insertPlainText(str)      #光標處插入普通文本
QTextEdit.toPlainText()             #普通文本獲取

b.html標簽文本設定,用法和普通文本一樣

QTextEdit.setHtml('str')
QTextEdit.insertHtml('str')
QTextEdit.toHtml()

c.還可以自動設置文本

QTextEdit.setText('str')

這個可以自動設置文本。

d.其余API

QTextEdit.append('str')     #文本追加(不管光標位置)
QTextEdit.clear()           #文本清除

文本追加時也是自動判定的,它不管光標的位置直接在文本后追加文本(另起一行)

三.文本光標

在上面的部分我們介紹了一種通過類提供的方法改變文本內容的方法,這里講的是另一種:通過文本光標來操作文本框的內容。

首先來了解一下什么叫文本光標:通常我們在編輯文本文件時,是通過一個文本編輯器(就想word)操作的。word和文本文檔在內存中建立了對應的關系,通過一個叫‘文本光標’的抽象的對象在內存中對文本文檔進行操作。我們可以通過文本光標對QTextEdit進行各種操作。

獲取光標,在獲取光標后,就可以進行一系列的操作了。

te = QTextEdit(window)
tc = te.textCursor()      #獲取光標

為了演示,我們建立一個界面,界面上一個按鈕btn,一個QTextEdit,btn對應了一個槽函數fun,為了演示不同的效果,在下面的代碼中值改變fun函數,先把大的框架放出來

from PyQt5.Qt import *
import sys
app=QApplication(sys.argv)
window = QWidget()
te = QTextEdit(window)
window.resize(800,600)
btn = QPushButton('test',window)
btn.move(0,300)
def fun():
    return None

btn.clicked.connect(fun)
window.show()
sys.exit(app.exec_())
文本光標程序框架

1.插入文本

def fun():
    tc = te.textCursor()
    tcf = QTextCharFormat()    #定義插入的文本格式
    tcf.setFontFamily('隸屬')  #定義格式字體
    tcf.setFontPointSize(30)   #定義格式字體大小
    tc.insertText('插入文本',tcf) #按格式插入字體
    tc.insertHtml("<a href='http://www.baidu.com'> 百度</a>")  #插入html文本(超鏈接)

如果想查看具體的格式設置,可以按下Ctrl鍵點擊QTextCharFormat看看里面的構造函數,我們在后面還會再詳細講解。這里插入的超鏈接由於設置的關系不能用鼠標點擊,但是已經有超鏈接的外觀效果了。還有一種是插入文本片段

def fun():
    tc = te.textCursor()
    tdf = QTextDocumentFragment().fromPlainText('123')   #插入普通文本片段
    tc.insertFragment(tdf)
    tdf2 = QTextDocumentFragment.fromHtml("<a href='http://www.baidu.com'> 百度</a>") #插入html標簽文本片段
    tc.insertFragment(tdf2)

2.插入圖片

def fun():
    tc = te.textCursor()
    pic = QTextImageFormat()
    pic.setName('picture.png')   #圖片路徑
    pic.setHeight(50)            #圖片高度
    pic.setWidth(50)             #圖片寬度
    tc.insertImage(pic)          #插入圖片

這里的picture.png是在同目錄下一個圖片。還有幾個已經過期但還可用的API,可以了解一下

tc.insertImage(pic,QTextFrameFormat)          #按格式插入圖片
tc.insertImage('picture.png')                 #直接按文件名插入圖片

3.插入列表

還可以在QTextEdit里插入一個列表,在輸入文字的時候可以有下面的效果

就像自動的段落編號一樣,可以在每次換行的時候自動生成一個列表編號或樣式。設置的API

def fun():
    tc = te.textCursor()
    tlf = QTextListFormat.ListCircle
    tc.insertList(QTextListFormat.ListCircle)   #插入列表,並把光標右邊的字符置為列表第一項
    tc.insertList(tlf) #在當前位置插入一個新塊,並使其成為具有給定格式的新創建列表的第一個列表項,返回創建的列表
    tc.createList(QTextListFormat.ListCircle)   #創建列表,並把光標所在行(段落)的字符置為列表第一項
    tc.createList(tlf)
#常用列表樣式枚舉值
    QTextListFormat.ListDisc       #圓點
    QTextListFormat.ListCircle     #空心圓
    QTextListFormat.ListSquare     #方塊
    QTextListFormat.ListDecimal    #數字升序
    QTextListFormat.ListUpperRoman #大寫羅馬數字
    QTextListFormat.ListLowerRoman #小寫羅馬數字
    QTextListFormat.ListUpperAlpha #大寫拉丁字母
    QTextListFormat.ListLowerAlpha #小寫拉丁字母

除了上面的枚舉值,還有另外一種設定方法

def fun():
    tc = te.textCursor()
    tlf = QTextListFormat()
    tlf.setIndent(3)                            #設定縮緊
    tlf.setNumberPrefix('<<')                  #如果列表值為數字,設定數字前綴
    tlf.setNumberSuffix('>>>')                 #如果列表值為數字,設定數字后綴
    tlf.setStyle(QTextListFormat.ListDecimal)  #樣式設置
    t2 = tc.insertList(tlf)

出來就是這樣的效果

 

4.插入表格

可以在文本塊內插入表格

def fun():
    tc = te.textCursor()
    # tc.insertTable(10,5)      #直接插入表格(行,列)
    ttf = QTextTableFormat()    #創建表格對象格式
    tc.insertTable(10,5,ttf)    #按格式插入表格

下面是常用的格式定義

ttf = QTextTableFormat()                 #創建表格對象格式
ttf.setCellPadding(10)                   #單元格內文本和邊框距離
ttf.setCellSpacing(20)                   #單元格線寬
ttf.setAlignment(Qt.AlignRight)          #對齊模式
def headerRowCount(self) -> int: ...
    def setHeaderRowCount(self, count: int) -> None: ...
    def setAlignment(self, aalignment: typing.Union[QtCore.Qt.Alignment, QtCore.Qt.AlignmentFlag]) -> None: ...
    def setCellPadding(self, apadding: float) -> None: ...
    def setColumns(self, acolumns: int) -> None: ...
    def alignment(self) -> QtCore.Qt.Alignment: ...
    def cellPadding(self) -> float: ...
    def setCellSpacing(self, spacing: float) -> None: ...
    def cellSpacing(self) -> float: ...
    def clearColumnWidthConstraints(self) -> None: ...
    def columnWidthConstraints(self) -> typing.List[QTextLength]: ...
    def setColumnWidthConstraints(self, constraints: typing.Iterable[QTextLength]) -> None: ...
    def columns(self) -> int: ...
    def isValid(self) -> bool: ...
QTextTableFormat內容

 插入表格時,把插入的表格賦值給一個變量,還可以對這個表格進行一系列QTextTable里的各種操作,這里列舉幾個效果

def fun():
    tc = te.textCursor()
    ttf = QTextTableFormat()
    ttf.setCellPadding(10)
    table = tc.insertTable(3,2,ttf)
    table.appendColumns(3)      #追加列
    table.appendRows(2)         #追加行
    table.mergeCells(1,2,2,3)   #合並單元格(第1行第2列開始,合並2行3列)

下面是QTextTable里的各種功能。

class QTextTable(QTextFrame):

    def __init__(self, doc: QTextDocument) -> None: ...

    def appendColumns(self, count: int) -> None: ...
    def appendRows(self, count: int) -> None: ...
    def setFormat(self, aformat: QTextTableFormat) -> None: ...
    def format(self) -> QTextTableFormat: ...
    def rowEnd(self, c: QTextCursor) -> QTextCursor: ...
    def rowStart(self, c: QTextCursor) -> QTextCursor: ...
    @typing.overload
    def cellAt(self, row: int, col: int) -> QTextTableCell: ...
    @typing.overload
    def cellAt(self, position: int) -> QTextTableCell: ...
    @typing.overload
    def cellAt(self, c: QTextCursor) -> QTextTableCell: ...
    def columns(self) -> int: ...
    def rows(self) -> int: ...
    def splitCell(self, row: int, col: int, numRows: int, numCols: int) -> None: ...
    @typing.overload
    def mergeCells(self, row: int, col: int, numRows: int, numCols: int) -> None: ...
    @typing.overload
    def mergeCells(self, cursor: QTextCursor) -> None: ...
    def removeColumns(self, pos: int, num: int) -> None: ...
    def removeRows(self, pos: int, num: int) -> None: ...
    def insertColumns(self, pos: int, num: int) -> None: ...
    def insertRows(self, pos: int, num: int) -> None: ...
    def resize(self, rows: int, cols: int) -> None: ...
QTextTable功能

在使用表格時,常常需要對表格的列寬進行約束,先了解一下列寬約束的API

def setColumnWidthConstraints(self, constraints: typing.Iterable[QTextLength]) -> None: ...

可以看出來,函數傳遞參數的是一個可迭代的對象,並且定義了typing(QTextLength的構造函數標注了兩種長度值:百分比(PercentageLength)和像素值(FixedLength))所以用起來是這樣的

def fun():
    tc = te.textCursor()
    ttf = QTextTableFormat()
    # ttf.setColumnWidthConstraints((QTextLength(QTextLength.PercentageLength,60),QTextLength(QTextLength.PercentageLength,40))) #百分比定義列寬
    ttf.setColumnWidthConstraints((QTextLength(QTextLength.FixedLength,80),QTextLength(QTextLength.FixedLength,70)))             #像素定義列寬
    table = tc.insertTable(3,2,ttf)

5.插入文本塊

這里說的文本塊就是一個用回車鍵分隔的段落(block),是可以帶有一定格式或樣式的。插入文本塊有這三種方法

insertBlock()                                #插入空文本塊
insertBlock(QTextBlockFormat)                #插入文本塊的同時設置文本塊格式
insertBlock(QTextBlockFormat,QTextCharFormat)#插入文本塊同時設置文本塊格式和字符格式

注意的是第三種,要明白文本塊格式和字符格式的區別:由於文本塊是一個段落,就會有縮進、對齊方式、間距等,而單個的字符格式就是字體、顏色、背景色等等。

def fun():
    tc = te.textCursor()
    tbf = QTextBlockFormat()   #文本塊格式
    tbf.setIndent(2)
    tcf = QTextCharFormat()    #字體格式
    tcf.setFontPointSize(20)
    tc.insertBlock(tbf,tcf)
    te.setFocus()

6.插入框架

在文本框內還可以插入一個框架,像下面的效果

在文本框內的框架里還可以輸入字符,用法是這樣的

def fun():
    tc = te.textCursor()
    tff = QTextFrameFormat()
    tff.setBorder(5)
    # tff.setBackground('cyan')
    tc.insertFrame(tff)

 用文本框架可以把一個大的框架分出多個小框架

def fun():
    tc = te.textCursor()
    tff = QTextFrameFormat()
    tff.setBorder(5)
    tff.setBorderBrush(QColor(50,50,50))
    tff.setRightMargin(30)

    doc = te.document()
    root_frame = doc.rootFrame()
    root_frame.setFrameFormat(tff)

    tc.insertFrame(tff)

出來的效果

可以給小的框架里放內容,還可以設置小框的樣式。

7.光標選中

用代碼實現光標的選中有個反向設置的概念

def fun():
    tc = te.textCursor()
    tc.setPosition(2,QTextCursor.KeepAnchor)
    te.setTextCursor(tc)                        #光標反向設置
    te.setFocus()

注意,這里先定義了光標,在把光標重新設置給QTextEdit控件。光標的移動有下面幾種方法

a.方式1:指定移動到的位置

setPosition(self, pos: int, mode: 'QTextCursor.MoveMode' = ...)   
#移動模式
QTextCursor.KeepAnchor   #保持錨點(選中效果)
QTextCursor.MoveAnchor   #移動錨點(無選中效果)

只要指定好目標位置,光標可以直接移動到目標位置,移動模式決定了是否有選中的功能。

b.方式2:按效果移動光標

movePosition(self, op: 'QTextCursor.MoveOperation', mode: 'QTextCursor.MoveMode' = ..., n: int = ...)
NoMove = ...  # type: 'QTextCursor.MoveOperation'
Start = ...  # type: 'QTextCursor.MoveOperation'
Up = ...  # type: 'QTextCursor.MoveOperation'
StartOfLine = ...  # type: 'QTextCursor.MoveOperation'
StartOfBlock = ...  # type: 'QTextCursor.MoveOperation'
StartOfWord = ...  # type: 'QTextCursor.MoveOperation'
PreviousBlock = ...  # type: 'QTextCursor.MoveOperation'
PreviousCharacter = ...  # type: 'QTextCursor.MoveOperation'
PreviousWord = ...  # type: 'QTextCursor.MoveOperation'
Left = ...  # type: 'QTextCursor.MoveOperation'
WordLeft = ...  # type: 'QTextCursor.MoveOperation'
End = ...  # type: 'QTextCursor.MoveOperation'
Down = ...  # type: 'QTextCursor.MoveOperation'
EndOfLine = ...  # type: 'QTextCursor.MoveOperation'
EndOfWord = ...  # type: 'QTextCursor.MoveOperation'
EndOfBlock = ...  # type: 'QTextCursor.MoveOperation'
NextBlock = ...  # type: 'QTextCursor.MoveOperation'
NextCharacter = ...  # type: 'QTextCursor.MoveOperation'
NextWord = ...  # type: 'QTextCursor.MoveOperation'
Right = ...  # type: 'QTextCursor.MoveOperation'
WordRight = ...  # type: 'QTextCursor.MoveOperation'
NextCell = ...  # type: 'QTextCursor.MoveOperation'
PreviousCell = ...  # type: 'QTextCursor.MoveOperation'
NextRow = ...  # type: 'QTextCursor.MoveOperation'
PreviousRow = ...  # type: 'QTextCursor.MoveOperation'
移動方式枚舉值

 有些移動方式是可以加個量值的,例如Left,加個n就是向左移動n個字符。

c.方式3:直接選中(不用設置光標移動模式,直接有選中效果)

select(QTextCursor.Document)   #選中效果
#選中效果枚舉值
QTextCursor.WordUnderCursor   # 當前光標下的單詞
QTextCursor.LineUnderCursor   # 當前光標下的行
QTextCursor.BlockUnderCursor  # 當前光標下的段落
QTextCursor.Document          # 整個文檔

 8.獲得選中

a.選中內容 的獲取

def fun():
    tc =te.textCursor()
    tc.selectedText()       #獲取選中的文本(返回值為字符串)
    tc.selection()          #獲取文本片段對象(返回值為QTextDocumentFragment,里面有各種功能)
    tc.selectedTableCells() #獲取選中的表格(左上行,左上列,右下行,右下列)

這里要注意的是,

  1.選中的片段對象可以進行QTextDocumentFragment類里的多種操作(取值、判定是否為空)等等

  2選中的表格必須是多個表格(cells),如果只選中一個表格則返回值為(-1,-1,-1,-1)。

b.選中位置的獲取

def fun():
    tc =te.textCursor()
    tc.selectionStart()    #獲取選中起始位置
    tc.selectionEnd()      #獲取選中結束位置

9.選中的取消和判定

a.選中的取消

選中的取消也是需要反向設定給TextCursor的

def fun():
    tc = te.textCursor()
    tc.clearSelection()    #取消選中
    te.setTextCursor(tc)   #反向設定
    te.setFocus()

為了體現效果,在設定完成后設置焦點。

b.選中的判定

def fun():
    tc = te.textCursor()
    tc.hasSelection()       #判定是否有選中,返回布爾量

c.選中的移除

通過代碼可實現把選中的內容刪除

def fun():
    tc = te.textCursor()
    tc.removeSelectedText()  #刪除選中內容

10.刪除效果

可以通過代碼實現刪除鍵(Backspace鍵或Delete鍵)的效果

def fun():
    tc = te.textCursor()
    tc.deleteChar()         #刪除光標后內容(Delete鍵)
    tc.deletePreviousChar() #刪除光標前內容(Backspace鍵)

如果刪除時無選中內容就刪除光標前/后內容,但如果有選中內容時刪除選中內容。

11.光標位置

獲取光標位置或對其位置進行判定

def fun():
    tc = te.textCursor()
    tc.columnNumber()
#枚舉值
QTextCursor.atBlockStart()   #是否在段落起始
QTextCursor.atBlockEnd()     #是否在段落結尾
QTextCursor.atStart()        #是否在文檔開始
QTextCursor.atEnd            #是否在文檔結束
QTextCursor.position()       #獲取光標在文檔中位置——>int
QTextCursor.positionInBlock()#獲取光標在段落中位置——>int
QTextCursor.columnNumber()   #獲取光標在第幾列——>int

 12.開始和結束編輯操作

在對文檔進行編輯時時可以直接多步驟進行撤銷和重做的,這就需要一個對整段操作做一個標記

def fun():
    tc = te.textCursor()
    tc.beginEditBlock()     #開始編輯
    tc.insertText('123')
    tc.insertBlock()
    tc.insertText('456')
    tc.insertBlock()
    tc.insertText('789')
    tc.insertBlock()
    tc.endEditBlock()       #結束編輯

這時候再進行撤銷,就是撤銷從開始編輯到結束編輯之間的過程。

四.直接設置文本框

在上一節我們是用文本光標對文本框進行操作,但是需要先建立文本光標。其實有些操作是可以直接通過文本框來實現的。

1.自動格式化

外觀效果和文本光標的插入列表有些像

def fun():
    te.setAutoFormatting(QTextEdit.AutoBulletList)
#枚舉值
QTextEdit.AutoNone
QTextEdit.AutoBulletList   
QTextEdit.AutoAll

現在只支持了AutoBulletList一種效果,就是在點擊“*”鍵后自動彈出列表

2.換行模式

換行模式有兩種,一種是不進行軟換行,在文本長度超出控件后產生水平滾動條,另一種是超出顯示范圍后進行軟換行

但是軟換行還有一個點:保持單詞的完整性,如果換行會破壞單詞的完整,則在單詞前進行換行

換行方式1:直接設置(因為默認的情況都是直接換行的,這里就放出來不換行的方式)

te.setLineWrapMode(QTextEdit.NoWrap)    #設置換行模式(不換行)

換行方式2:指定固定寬度,這種方式要結合QTextEdit.setLineWrapColumnOrWidth()來使用。這個代碼可以是列數也可以是寬度,取決於上面的代碼

te.setLineWrapMode(QTextEdit.FixedPixelWidth)    #按像素限制換行
te.setLineWrapMode(QTextEdit.FixedColumnWidth)   #按列數限制換行
te.setLineWrapColumnOrWidth(5)        

如果用像素限制的化下面的數值就要填像素值,而用列數限制了則下面的數值要填列數,上面的案例就是限制在5列。

換行方式3:保持單詞的完整性:

由於有些時候進行軟換行,單詞可能會被截斷,可以保持其完整性

te.setWordWrapMode(QTextOption.WordWrap)    #保持單詞完整

 還可以對換行模式、單詞換行模式進行獲取

QTextEdit.lineWrapMode()   #獲取換行模式
QTextEdit.wordWrapMode()   #獲取單詞換行模式

獲取的值是int,可以查詢QTextEdit.LineWrapMode和QtGui.QTextOption.WrapMode里面的內容,對返回值進行了定義。

3.覆蓋模式

覆蓋模式就是鍵盤上Insert的按鍵是一樣的,可以在新增字符是切換插入和替換的效果

QTextEdit.setOverwriteMode(True)   #覆蓋模式
QTextEdit.overwriteMode()          #獲取是否位覆蓋模式——>bool

4.光標設置

QTextEdit.setCursorWidth(int)   #設定光標寬度
QTextEdit.cursorWidth()         #獲取光標寬度——>int
QTextEdit.cursorRect()          #獲取光標區間——>QRect

 5.對齊設置

QTextEdit.setAlignment(Qt.AlignRight)
#對齊枚舉值
Qt.AlignCenter
Qt.AlignLeft
Qt.AlignRight

 五.字體設置

通過代碼,可以對文本框里的字體進行字體、樣式、尺寸等效果的設置,有

1.設置字體

te = QTextEdit(window)
te.setFontFamily('仿宋')    #設置字體
te.fontFamily              #獲取字體設置

在設置FontFamily的時候,有個小技巧,可以用QFontDialog.getFont()來查看可用的字體和字體能使用的效果

QFontDialog.getFont()  #顯示字體對話框

2.字體樣式

字體樣式主要分為字體粗細和字體斜體(字體對話框內Style里的部分),粗細由枚舉值新設定,而斜體則由布爾量設定

te = QTextEdit(window)
te.setFontWeight(QFont.Bold)    #設定粗細
te.fontWeight()                 #獲取粗細——>int
te.setFontItalic(True)          #設定斜體
te.fontItalic()                 #獲取是否設定為斜體
Thin = ...  # type: 'QFont.Weight'
ExtraLight = ...  # type: 'QFont.Weight'
Light = ...  # type: 'QFont.Weight'
Normal = ...  # type: 'QFont.Weight'
Medium = ...  # type: 'QFont.Weight'
DemiBold = ...  # type: 'QFont.Weight'
Bold = ...  # type: 'QFont.Weight'
ExtraBold = ...  # type: 'QFont.Weight'
Black = ...  # type: 'QFont.Weight'
粗細枚舉值
 
        

這里有個問題,PyQt5的源代碼里定義的是設定粗細給定的是個int的數據,但是不能用,需要給QFont里的枚舉值

def setFontWeight(self, w: int) -> None: ...

3.字體尺寸

te = QTextEdit(window)
te.setFontPointSize(30)   #設定尺寸(float)
te.fontPointSize()        #獲取尺寸——>float

4.字體效果

字體效果主要是下划線效果(在光標設置字體里還有其他的效果,但通過對話框直接操作只有下划線)

te = QTextEdit(window)
te.setFontUnderline(True)   #下划線
te.fontUnderline()          #獲取是否啟用下划線

 5.統一設置

可以用QFont()的功能來對字體進行統一設置

te = QTextEdit(window)
font=QFont()
font.setStrikeOut(True)
te.setCurrentFont(font)

可以看一下QFont的構造函數,提供了這樣的用法

def __init__(self, family: str, pointSize: int = ..., weight: int = ..., italic: bool = ...) -> None: ...

就是說我們在生命font的時候可以直接把字體樣式帶進去

font=QFont('隸書',-1,10,True)

這樣就是說字體是隸書,像素點用默認值,字體粗細為10,斜體使用。

6.字體顏色

字體顏色分字體的顏色和字體背景色

te = QTextEdit(window)
te.setTextBackgroundColor(QColor('green'))       #設定背景色
te.textBackgroundColor()                         #獲取背景色對象——>QColor object
te.setTextColor(QColor('red'))                   #改變字體顏色
te.textColor()                                   #獲取字體顏色

7.利用QTextCharFormat設置字體

我們在文本光標里使用了QTextCharFormat對字體進行設置。

te = QTextEdit(window)
tcf =QTextCharFormat()
tcf.setFontPointSize(30)
te.setCurrentCharFormat(tcf)

注意這里的設定使用的setCurrentCharFormat,和上面字體設置(setCurrentFont)是不太一樣的。還有幾個枚舉值挺有用的,這里羅列一下

tcf =QTextCharFormat()
tcf.setFontCapitalization(QFont.SmallCaps)  #字母大小寫設定
tcf.fontCapitalization()                    #獲取字母大小寫設置——>int
te.setCurrentCharFormat(tcf)
#大小寫設定枚舉值
QFont.MixedCase      # 常規
QFont.AllUppercase     # 所有字母大寫
QFont.AllLowercase     # 所有字母小寫
QFont.SmallCaps      # 小型化的大寫字母
QFont.Capitalize     #首字母大寫

還有

tcf.setFontOverline()      #上划線
tcf.setFontStrikeOut()     #中划線

等等,可以查看QTextCharFormat里的定義。但是用

te.setCurrentCharFormat(tcf)

是設置新的字體,還得意合並字體設置

tcf =QTextCharFormat()                
te.setCurrentCharFormat(tcf)
tcf2 = QTextCharFormat()
te.mergeCurrentCharFormat(tcf2)   #把tcf2里的字體設置追加進去

這樣就是把tcf2里的設置追加給tcf。

8.常規操作

先是常規的復制粘貼等操作

te = QTextEdit()
te.copy()
te.paste()
te.canPaste()
te.setUndoRedoEnabled()
te.undo()
te.redo()
te.selectAll()

這就是字面的意思,就不備注了,還有一個是搜索,要拿出來單講一下

te.find(str,options=)

查找是的選項有幾個枚舉值

QTextDocument.FindBackward          #從后向前查找
QTextDocument.FindCaseSensitively   #默認查找不區分大小寫,使用該枚舉值啟用區分大小寫查找
QTextDocument.FindWholeWords        #找完整的單詞

這三個枚舉值是不沖突的,可以用或運算符"|"連接使用。例如

te.find('abc',QTextDocument.FindWholeWords|QTextDocument.FindCaseSensitively|QTextDocument.FindBackward)

就是只能查找光標左邊abc的單詞,加入有個abcd或Abcd是不行的。

9.只讀設置

te = QTextEdit(window)
te.setReadOnly(True)   #設置位只讀模式
te.isReadOnly()        #獲取是否位只讀模式

要注意兩點,1.這里的只讀模式只是對用戶是只讀的,利用代碼還是可以修改文本框的內容的。

      2.設置位只讀模式后右鍵出來的菜單只有復制和全選了,其余粘貼啥的都沒有了。

10.tab鍵設置

因為在界面里的控件可以通過tab鍵切換焦點,但是在文本框里有時候也是用得到tab鍵的,那會不會沖突啊?可以這么設定

window = MyWindow()
te = QTextEdit(window)
te.setTabChangesFocus(True)   #tab鍵切換焦點

tab鍵默認在文本框里是制表符的,上面的代碼可以強制切換焦點。還可以設置制表符的距離像素值

te.setTabStopWidth(100)     #設置制表符的距離(像素)
te.tabStopWidth()           #獲取制表符的距離——>int

11.滾動到錨點

可以在文本中設定一個錨點(Anchor)通過按鈕連接函數實現直接跳轉到這個點處。

from PyQt5.Qt import *
import sys
app=QApplication(sys.argv)
class MyWindow(QWidget):
    pass




window = MyWindow()
te = QTextEdit(window)

te.insertHtml('x x x'*30+"<a name='anchor' href='baidu'>百度</a>"+'b b b'*50)
te.insertPlainText('aaa'*30)
btn = QPushButton('click',window)
btn.move(200,200)
def fun():
    te.scrollToAnchor('anchor')
    pass

btn.clicked.connect(fun)

window.show()
sys.exit(app.exec_())
滾動到錨點

錨點的設置

<a name ="錨點名稱"href='錨點內容'>xxx</a>

六.常用信號

1.文本內容發生改變時發射的信號

QTextEdit.textChanged()

2.選中文本內容發生改變時發射的信號

QTextEdit.selectionChanged()

3.光標位置發生改變時發射的信號

QTextEdit.cursorPositionChanged()

4.當前字符格式發生改變時發射的信號(帶有參數)

QTextEdit.currentCharFormatChanged(QTextCharFormat) #參數QTextCharFormat

5.復制可用時(返回布爾量)

QTextEdit.copyAvailable(bool)

6.重做可用時(返回布爾量)

QTextEdit.redoAvailable(bool)

7.撤銷可用時(返回布爾量)

QTextEdit.undoAvailable(bool)

七.利用事件實現打開超鏈接的效果

我們在上面實現了在文本框內插入超鏈接,可以不能打開,那怎么實現超鏈接的打開呢?

1.利用事件

2.利用錨點的特性

anchorAt(self, pos: QtCore.QPoint) -> str: ...

如果Point在錨點上會返回錨點對應的字符串。總之,代碼就是這樣的

from PyQt5.Qt import *
from PyQt5 import QtGui
import sys
app=QApplication(sys.argv)
class MyWindow(QWidget):
    pass

class TextEdit(QTextEdit):
    def mousePressEvent(self, e: QtGui.QMouseEvent):         #對鼠標點擊事件進行重構
        link_str = self.anchorAt(e.pos())                    #如果標點擊位置在錨點上返回鏈接地址
        if len(link_str)>0:                                  #如果有鏈接地址
            QDesktopServices.openUrl(QUrl(link_str))         #打開超鏈接

window = MyWindow()
window.resize(500,600)
te = TextEdit(window)
te.insertHtml("<a name ='anchor' href='http://www.baidu.com'>百度</a>")  #插入超鏈接時加上錨點
window.show()
sys.exit(app.exec_())
打開超鏈接

結束!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM