How to format selected text in QTextEdit by clicking a button

I want to format the selected text in QTextEdit by clicking a button. For axample, I want to make it bold if it is not bold, or non-bold if it is in bold. Please help me with an example.

EDIT:

In fact, I already found the qt demo code for a text editor that does what I need:

void
MyTextEdit::boldText(bool isBold) //this is the SLOT for the button trigger(bool)
{
    QTextCharFormat fmt;
    fmt.setFontWeight(isBold ? QFont::Bold : QFont::Normal);
    mergeFormatOnWordOrSelection(fmt);
}

void
MyTextEdit::mergeFormatOnWordOrSelection(const QTextCharFormat &format)
 {
     QTextCursor cursor = m_textEdit->textCursor();
     if (!cursor.hasSelection())
         cursor.select(QTextCursor::WordUnderCursor);
     cursor.mergeCharFormat(format);
     m_textEdit->mergeCurrentCharFormat(format);
 }

But I can’t understand what the textCursor () method returns and how the property merge is done? Just some formats change, some of them remain constant. As a function, mergeCharFormat understands what to change and what to leave as is. Please explain to me only these two things. Thank.

+3
1

TextCursor() textCursor, , textEdit, . QTextCursor Qt, , , , , .

mergeCharFormat, , (, , ) . , , , .

, .

+3

Source: https://habr.com/ru/post/1763093/


All Articles