使用 PyQt6 切換字元格式

PHPz
發布: 2024-02-09 18:57:03
轉載
651 人瀏覽過

使用 PyQt6 切换字符格式

問題內容

我正在編寫一個自訂文字處理器作為一個業餘愛好項目。我正在使用 python 和 pyqt6。

我寫了以下內容。目的是,如果我選擇一些文字並應用粗體格式(例如,點擊“ctrl-b”),它將切換格式。具體來說,如果所有選定的文字都是粗體,則應刪除粗體格式。否則,它將套用粗體格式。

class OvidFont:
    def __init__(self, ovid) -> None:
        self.textEditor = ovid.textEditor

    def setBoldText(self) -> None:
        fmt = QTextCharFormat()
        if self.textEditor.currentCharFormat().fontWeight() != QFont.Weight.Bold:
            print("    setting bold")   # for debugging
            fmt.setFontWeight(QFont.Weight.Bold)
        else:
            print("    setting normal") # for debugging
            fmt.setFontWeight(QFont.Weight.Normal)
        self.textEditor.textCursor().mergeCharFormat(fmt)
登入後複製

但是,它不會刪除粗體格式。

例如,在句子“this is a test”中,如果我選擇“is a”並應用粗體格式,我會得到“this is a test”,其中“is a” “適當大膽。然而,選擇到位後,如果我點擊“ctrl-b”,它仍然保持粗體。如果我取消選擇第一個或最後一個字符,粗體切換將按預期工作。(我嘗試過反轉if /else 邏輯,但也失敗了)。

我錯過了什麼?

更新:我在https://gist.github.com/ovid/65936985c6838c0220620cf40ba935fa 新增了一個有效的最小測試案例


#正確答案


######################################## #setboldtext### 函數的問題在於它使用###self.texteditor.currentcharformat().fontweight()### 檢查粗體狀態,這僅反映當前遊標位置處字元的格式,而不是整個選定文本的格式。如果您的遊標位於所選內容的開頭或結尾,它可能無法準確表示整個所選範圍的格式。 ### ###因此,我使用現有的遊標,並根據需要進行調整以檢查格式,並在 ###setfontweight()### 上直接套用新的字體粗細。 ### ###現在看起來像這樣:### ######更新的程式碼:#######
import sys
from PyQt6.QtWidgets import QTextEdit, QToolButton, QApplication, QMainWindow, QToolBar
from PyQt6.QtGui import QFont, QShortcut, QKeySequence, QTextCharFormat, QTextCursor

class OvidFont:
    def __init__(self, ovid) -> None:
        self.textEditor = ovid.textEditor

    def setBoldText(self):
        cursor = self.textEditor.textCursor()

        # If there's a selection, and the cursor is not at the block start and at the beginning of the selection,
        # move the cursor to the end of the selection
        if cursor.hasSelection() and not cursor.atBlockStart() and cursor.position() == cursor.selectionStart():
            cursor.setPosition(cursor.selectionEnd())

        # Check if the text (either selected or where the cursor is) is bold
        is_bold = cursor.charFormat().fontWeight() == QFont.Weight.Bold

        # Apply the new weight based on the current state
        new_weight = QFont.Weight.Normal if is_bold else QFont.Weight.Bold
        self.textEditor.setFontWeight(new_weight)

        print(f"Bold set to: {'Normal' if is_bold else 'Bold'}")

class Ovid(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("Ovid")
        self.setGeometry(100, 100, 200, 200)
        self.textEditor = QTextEdit()
        self.setCentralWidget(self.textEditor)
        self.fonts = OvidFont(self)

        self.toolbar = QToolBar("Main Toolbar")
        self.addToolBar(self.toolbar)

        bold_button = QToolButton()
        bold_button.setText("B")
        bold_button.setFont(QFont("Arial", 16, QFont.Weight.Bold))
        bold_button.setToolTip("Bold")
        bold_button.clicked.connect(self.fonts.setBoldText)
        self.toolbar.addWidget(bold_button)

        QShortcut(QKeySequence("Ctrl+B"), self, self.fonts.setBoldText)

def main():
    app = QApplication(sys.argv)
    ex = Ovid()
    ex.show()
    sys.exit(app.exec())

if __name__ == "__main__":
    main()
登入後複製

以上是使用 PyQt6 切換字元格式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!