PyQt6 Not toggling "bold" text.

Charles peacech at gmail.com
Fri Jan 26 11:05:43 GMT 2024


Hi,

Other than Google and AI, searching code in github is also an alternative:
searching for mergeCharFormat yields

https://github.com/kovidgoyal/calibre/blob/07f988b109627bdbb88ab4b43ccfa6956276c682/src/calibre/gui2/comments_editor.py#L465

>From the look of it, your code is missing
`self.textEditor.setTextCursor(...)` because `textCursor()` returns a copy.

On Fri, Jan 26, 2024 at 5:50 PM Ovid <curtis.poe at gmail.com> wrote:

> Hi all,
>
> Google and ChatGPT and Copilot have failed me!
>
> I'm writing a custom word processor as a hobby project. I'm using Python
> and PyQt6.
>
> I wrote the following. The intent is that if I select some text and apply
> Bold formatting (for example, by hitting "ctrl-b"), it will toggle the
> formatting. Specifically, it should remove the bold formatting if all of
> the selected text is bold. Otherwise, it will apply the bold formatting.
>
>     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)
>
> However, it won't remove the bold formatting.
>
> For example, in the sentence "this is a test", if I select "is a" and hit
> ctrl-b, I get "this **is a** test", with the "is a" properly bold. However,
> with the selection in place, it still remains bold if I hit "ctrl-b". If I
> deselect either the first or last character, the toggling of bold works as
> expected. (I've tried reversing the if/else logic, but that fails, too).
>
> What am I missing?
>
> Cheers,
> Ovid
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.riverbankcomputing.com/pipermail/pyqt/attachments/20240126/545282d7/attachment.htm>


More information about the PyQt mailing list