The block's character format is used when inserting text into an empty block, something you are not doing. You need to make a selection and then either QTextCursor::setCharFormat() or QTextCursor::mergeCharFormat().
#include <QtGui>
#include <QDebug>
int main(int argc, char **argv)
{
te.setText("Line 1\nLine 2\nLine 3");
int index = 0;
while (blk.isValid()) {
qDebug() << blk.text();
if (index == 1) {
format.setForeground(Qt::darkYellow);
format.setBackground(Qt::gray);
cursor.setCharFormat(format);
}
++index;
blk = blk.next();
}
te.show();
return app.exec();
}
#include <QtGui>
#include <QDebug>
int main(int argc, char **argv)
{
QApplication app(argc, argv);
QTextEdit te;
te.setText("Line 1\nLine 2\nLine 3");
QTextDocument *textDoc = te.document();
QTextBlock blk = textDoc->begin();
int index = 0;
while (blk.isValid()) {
qDebug() << blk.text();
if (index == 1) {
QTextCursor cursor(blk);
cursor.movePosition(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
QTextCharFormat format;
format.setForeground(Qt::darkYellow);
format.setBackground(Qt::gray);
cursor.setCharFormat(format);
}
++index;
blk = blk.next();
}
te.show();
return app.exec();
}
To copy to clipboard, switch view to plain text mode
Bookmarks