QT:设置qtextedit文本框中某个字符的格式

原文出处:http://blog.sina.com.cn/s/blog_a07a3f180102uyou.html


void Widget::setCharColor(unsigned int pos)

{

if(pos <= 0)return ;

QTextCursor cursor = ui->view1->textCursor();

cursor.movePosition( QTextCursor::StartOfLine );//行首

cursor.movePosition( QTextCursor::Right, QTextCursor::MoveAnchor, pos-1);//向右移动到Pos

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

ui->view1->setTextCursor( cursor ); // added

QTextCharFormat defcharfmt = ui->view1->currentCharFormat();

QTextCharFormat newcharfmt = defcharfmt;

newcharfmt.setFontUnderline( true );

newcharfmt.setUnderlineColor( QColor( Qt::red ) );

newcharfmt.setUnderlineStyle( QTextCharFormat::SingleUnderline );

ui->view1->setCurrentCharFormat( newcharfmt );

cursor.movePosition( QTextCursor::PreviousCharacter );//加上这句是为了去除光标selected

ui->view1->setTextCursor( cursor ); // added

// ui->view1->setCurrentCharFormat( defcharfmt );

ui->view1->setFocus();

}