目錄
#正確答案
首頁 後端開發 Python教學 使用 PyQt6 切換字元格式

使用 PyQt6 切換字元格式

Feb 09, 2024 pm 06:57 PM

使用 PyQt6 切换字符格式

問題內容

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

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()### 上直接套用新的字體粗細。 ### ###現在看起來像這樣:### ######更新的程式碼:#######

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

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中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱門文章

倉庫:如何復興隊友
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱門文章

倉庫:如何復興隊友
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱門文章標籤

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

我如何使用美麗的湯來解析HTML? 我如何使用美麗的湯來解析HTML? Mar 10, 2025 pm 06:54 PM

我如何使用美麗的湯來解析HTML?

python中的圖像過濾 python中的圖像過濾 Mar 03, 2025 am 09:44 AM

python中的圖像過濾

如何使用Python查找文本文件的ZIPF分佈 如何使用Python查找文本文件的ZIPF分佈 Mar 05, 2025 am 09:58 AM

如何使用Python查找文本文件的ZIPF分佈

如何使用Python使用PDF文檔 如何使用Python使用PDF文檔 Mar 02, 2025 am 09:54 AM

如何使用Python使用PDF文檔

如何在django應用程序中使用redis緩存 如何在django應用程序中使用redis緩存 Mar 02, 2025 am 10:10 AM

如何在django應用程序中使用redis緩存

如何使用TensorFlow或Pytorch進行深度學習? 如何使用TensorFlow或Pytorch進行深度學習? Mar 10, 2025 pm 06:52 PM

如何使用TensorFlow或Pytorch進行深度學習?

如何在Python中實現自己的數據結構 如何在Python中實現自己的數據結構 Mar 03, 2025 am 09:28 AM

如何在Python中實現自己的數據結構

Python中的平行和並發編程簡介 Python中的平行和並發編程簡介 Mar 03, 2025 am 10:32 AM

Python中的平行和並發編程簡介

See all articles