Cursor selection in QTextEdit reporting wrong font weight when selecting left-to-right or bottom-to-top

40 views Asked by At

I've built an application in Python that makes heavy use of QTextEdits. It has basic formatting buttons and hotkeys so that the user can change their font to Bold, Italic, and Underline. For the most part, these work well, but I'm experiencing some unexpected behavior that, while it is minor, could cause headaches for the average user.

Let's take bold text as an example. When dragging the mouse in a right-to-left direction over bold text, and your selection ends at the beginning of the bold text, cursor.charFormat().font().bold() reports the selection as 'False'.

To illustrate, if I have this text in my QTextEdit:

I'm a little bit foo bar

if I were to drag the mouse right-to-left over the word 'little' to select it, I cannot use the button or hotkey to un-bold that word because QT reports the selection as not being bold.

Dragging the mouse in a left-to-right direction causes no such problem. I would assume that is because of where the cursor actually stops and how QT reports the font attributes of the character prior to the cursor and not the character after.

Now, I've been able to remedy this by programmatically redoing the selection using

cursor.setPosition(selection_start, QTextCursor.MoveMode.MoveAnchor)
cursor.setPosition(selection_end, QTextCursor.MoveMode.KeepAnchor)

but that seems a little bit hack-y to me, and I'm thinking that there's a better way that I just don't know about.

Here's the function that gets called when using the bold button or the bold hotkey:

    def setBold(self):
        component = self.win.focusWidget()

        if isinstance(component, QTextEdit):
            cursor = component.textCursor()

            if cursor.hasSelection():
                selection_start = cursor.selectionStart()
                selection_end = cursor.selectionEnd()
                cursor.setPosition(selection_start, QTextCursor.MoveMode.MoveAnchor)
                cursor.setPosition(selection_end, QTextCursor.MoveMode.KeepAnchor)
                char_format = cursor.charFormat()

                if char_format.font().bold():
                    char_format.setFontWeight(QFont.Normal)
                    cursor.mergeCharFormat(char_format)
                else:
                    char_format.setFontWeight(QFont.Bold)
                    cursor.mergeCharFormat(char_format)

            else:
                font = cursor.charFormat().font()

                if font.weight() == QFont.Normal:
                    font.setWeight(QFont.Bold)
                    component.setCurrentFont(font)
                else:
                    font.setWeight(QFont.Normal)
                    component.setCurrentFont(font)

By the way, it's only the if cursor.hasSelection() block that is giving me the troubles. I'd sure appreciate your thoughts on this!

0

There are 0 answers