弄了好久吧,终于弄出来了。qt自带的帮助系统还真是挺好的,网上查了这么久资料,也没有找到具体的或者模糊的解决方法。只是说用html或者用QTextFormat及各种派生的类来改变文本框中字符格式,nnd,哥哥也知道可以用这个来实现。具体就没有了。废话少说,记录下来,以后用得着。这里用的是format。具体功能就是修改光标所在行的第pos个字符的格式,这里的格式是给字符加个下划线。其他格式,比如字符颜色、背景颜色也是如此,改下format就好了。
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();
}
常用格式:
【newcharfmt.setBackground(QColor("#EEEE00"));】
【newcharfmt.setFontPointSize(fontSize);】
【newcharfmt.setFontWeight(QFont::Bold);】
【highlightedFormat.setBackground(Qt::yellow);】
【newcharfmt.setForeground(Qt::red);】
注意:【上面的操作会促发textchanged槽函数,所以用到槽函数的时候注意下,加个标志判断下就好了】
说明:【curso.movePositon,,,//加上这句....ed】
不加上时效果如下:
加上时效果如下:
附:
版权声明:本文为博主[原创]文章,未经博主允许可以转载,注明博客出处:[http://blog.csdn.net/FreeApe]
时间: 2024-08-01 10:47:00