簡體   English   中英

如何在pyqt5中的QTextEditor中將所選文本加粗

[英]How to bold the selected text in QTextEditor in pyqt5

我有一個問題,這個問題是我無法將當前選定的文本設為粗體。 我選擇了部分文本,當我嘗試將當前選定的文本加粗時。 我把那部分的所有文字都加粗了。 那么問題出在哪里呢?

簡而言之。 我想把“愛”這個詞加粗

import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.uic import loadUiType
import sip



class Widget(QWidget):
    def __init__(self):
        super().__init__()
        self.setGeometry(500, 500, 700, 700)
        self.te = QTextEdit(self)
        self.te.setText('sad man loves sad women')

        self.button = QPushButton("bold the text", self)
        self.button.move(150, 200)
        self.button.clicked.connect(self.bold_text)

        self.document = self.te.document()
        self.cursor = QTextCursor(self.document)

    def bold_text(self):
        # bold the text
        
        self.cursor.movePosition(QTextCursor.Start)
        self.cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.KeepAnchor)
        self.format = QTextCharFormat()
        self.format.setFontWeight(QFont.Bold)
        self.cursor.mergeCharFormat(self.format)

if __name__ == "__main__":

    app = QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

你將光標移動到Start的文件,然后到EndOfLine 所以你在完整的第一行設置了粗體格式,完全忽略了選擇。

如果您想將當前選擇加粗,絕對不需要使用 QTextDocument 或 QTextCursor ,因為 QTextEdit 已經提供了setFontWeight()

    def bold_text(self):
        self.te.setFontWeight(QFont.Bold)

請注意,您不應使用對文本光標或文檔的持久引用:雖然它在您的簡單情況下有效,但光標或文檔都可能發生變化,因此您應該始終動態訪問它們。 此外,您可以使用 QTextEdit 的textCursor()直接訪問文本光標。

不相關,但仍然很重要:避免使用固定的幾何圖形,而總是更喜歡布局管理器

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM