我正在編寫一個自訂文字處理器作為一個業餘愛好項目。我正在使用 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中文網其他相關文章!

Python在自動化、腳本編寫和任務管理中表現出色。 1)自動化:通過標準庫如os、shutil實現文件備份。 2)腳本編寫:使用psutil庫監控系統資源。 3)任務管理:利用schedule庫調度任務。 Python的易用性和豐富庫支持使其在這些領域中成為首選工具。

要在有限的時間內最大化學習Python的效率,可以使用Python的datetime、time和schedule模塊。 1.datetime模塊用於記錄和規劃學習時間。 2.time模塊幫助設置學習和休息時間。 3.schedule模塊自動化安排每週學習任務。

Python在遊戲和GUI開發中表現出色。 1)遊戲開發使用Pygame,提供繪圖、音頻等功能,適合創建2D遊戲。 2)GUI開發可選擇Tkinter或PyQt,Tkinter簡單易用,PyQt功能豐富,適合專業開發。

Python适合数据科学、Web开发和自动化任务,而C 适用于系统编程、游戏开发和嵌入式系统。Python以简洁和强大的生态系统著称,C 则以高性能和底层控制能力闻名。

2小時內可以學會Python的基本編程概念和技能。 1.學習變量和數據類型,2.掌握控制流(條件語句和循環),3.理解函數的定義和使用,4.通過簡單示例和代碼片段快速上手Python編程。

Python在web開發、數據科學、機器學習、自動化和腳本編寫等領域有廣泛應用。 1)在web開發中,Django和Flask框架簡化了開發過程。 2)數據科學和機器學習領域,NumPy、Pandas、Scikit-learn和TensorFlow庫提供了強大支持。 3)自動化和腳本編寫方面,Python適用於自動化測試和系統管理等任務。

兩小時內可以學到Python的基礎知識。 1.學習變量和數據類型,2.掌握控制結構如if語句和循環,3.了解函數的定義和使用。這些將幫助你開始編寫簡單的Python程序。

如何在10小時內教計算機小白編程基礎?如果你只有10個小時來教計算機小白一些編程知識,你會選擇教些什麼�...


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

WebStorm Mac版
好用的JavaScript開發工具

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

Dreamweaver Mac版
視覺化網頁開發工具

禪工作室 13.0.1
強大的PHP整合開發環境

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。