PDA

View Full Version : How to set TextFormat of a TextBlock directly



wang9658
22nd May 2012, 16:14
textDoc = QTextEdit->document;
...

I want to set one line's color, but no effect. I think for the TextBlock of plaintext, block and line are same things.



QTextBlock blk = textDoc->begin();
int index = 0;
while(blk.isValid()){
qDebug() << "BLOCK:" << blk.text();
index++;
if(1){//index == 10){
QTextCursor cursor(blk);
QTextCharFormat format;
format.setForeground(Qt::darkYellow);
format.setBackground(Qt::gray);
cursor.setBlockCharFormat(format);
}
blk = blk.next();
}

ChrisW67
23rd May 2012, 00:05
Do you need to have a selection (i.e. selectionStart() then setPosition() or movePosition()) to apply a format to?

wang9658
23rd May 2012, 00:19
No selection.
I have a string list, if the lines in QTextEdit same as string in the string list, I'll highlight it. That's my purpose.

ChrisW67
23rd May 2012, 00:58
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)
{
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();
}

wang9658
23rd May 2012, 15:06
You are right, if make a selection, it works.
I tried your code. For plaintext, it should be

cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);


Thank you again.