wutzebaer
wutzebaer

Reputation: 14863

QTextEdit update single QTextCharFormat

I'm trying to update the QTextCharFormat for a single character. But it is not applied:

QTextCursor cursor(document());
cursor.setPosition(4);
QTextCharFormat format;
format.setFontPointSize(sizeString.toInt());
cursor.mergeCharFormat(format);
qDebug() << "SET POS " << cursor.position() << " TO " << sizeString.toInt();

QTextCursor cursor2(document());
cursor.setPosition(4);
QTextCharFormat charformat = cursor2.charFormat();
QFont font = charformat.font();
qDebug() << " LOADED FONTSIZE: " << font.pointSize();

Output:

SET POS  4  TO  16
 LOADED FONTSIZE:  36

Any idea what's missing?

Upvotes: 1

Views: 1900

Answers (2)

Hayt
Hayt

Reputation: 5370

For a change to apply you have to select a part of text (like in a real editor). You only set the cursor to a position without actually selecting things.

If you want to select text you have to move the cursor to another position with keeping the selection start.

cursor.setPosition(4);
cursor.setPosition(5, QTextCursor::KeepAnchor);

This sets the cursor to position 4. Then moves the cursor to position 5 but keeping the selection anchor. Which results in everything between position 4 and 5 being selected.

Now your changes will be applied to the selection.

Upvotes: 2

mohabouje
mohabouje

Reputation: 4050

Example of the correct usage:

Get the cursor of your QTextEdit

QTextEdit *editor = new QTextEdit();
QTextCursor cursor(editor->textCursor());
cursor.movePosition(QTextCursor::Start); 

Set up your different QTextCharFormat

QTextCharFormat plainFormat(cursor.charFormat());

QTextCharFormat headingFormat = plainFormat;
headingFormat.setFontWeight(QFont::Bold);
headingFormat.setFontPointSize(16);

QTextCharFormat emphasisFormat = plainFormat;
emphasisFormat.setFontItalic(true);

Now insert text in the text edit using different formats

cursor.insertText(tr("Character formats"),
                  headingFormat);

cursor.insertBlock(); // Single character
cursor.insertText(tr("a"), emphasisFormat);
cursor.insertText(tr("b"), headingFormat);
cursor.insertBlock();


cursor.insertText(tr("Text can be displayed in a variety of "
                              "different character formats. "), plainFormat);
cursor.insertText(tr("We can emphasize text by "));
cursor.insertText(tr("making it italic"), emphasisFormat);

If you want to change the style of a editable widget in real time of just render a text with different styles, you have an example in this url: Syntax Highlighter Example

Upvotes: 1

Related Questions