wutzebaer wutzebaer - 2 months ago 17
C++ Question

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?

Answer

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.

Comments