使用QT编写一个个性化消息输出框是发生:
QTextCursor::setPosition: Position ‘40’ out of range
QTextCursor::setPosition: Position ‘119’ out of range
QTextCursor::setPosition: Position ‘171’ out of range
QTextCursor::setPosition: Position ‘162’ out of range
QTextCursor::setPosition: Position ‘175’ out of range
QTextCursor::setPosition: Position ‘216’ out of range
原始代码:
void OutPutMsgToConsle(ConSleLevel level,const QString &strText)
{
//日志等级大于配置文件允许的最高等级,就返回
//可以用于消息弹出时中止此函数
// if (level > LocalConfig::GetInstance().GetCfgConsleLevel())
// {
// return;
// }
exportMessage->append(strText);
//选中需要显示颜色的文字
QTextCursor cursor = exportMessage->textCursor();
cursor.setPosition(cursor.position(),QTextCursor::MoveAnchor);//待删除
cursor.setPosition(cursor.position() + strText.length(),QTextCursor::KeepAnchor);//待删除
cursor.select(QTextCursor::BlockUnderCursor);//选择光标下的文本块,也可改成只选中单词,待删除
QTextCharFormat fmt;
//根据不同等级绘制不同颜色
// QPainter p(exportMessage);
switch (level)
{
case Critical_INFO:
fmt.setForeground(Qt::red);
break;
case Warning_INFO:
fmt.setForeground(QColor(255 ,193 ,37));//黄色
break;
case Running_INFO:
fmt.setForeground(Qt::green);
break;
case Information_INFO:
fmt.setForeground(Qt::black);
break;
default:
break;
}
cursor.mergeCharFormat(fmt);
cursor.clearSelection(); //撤销选中
cursor.movePosition(QTextCursor::EndOfBlock); //cursor和anchor均移至末尾
}
解决办法:把setPosition函数改用movePosition函数,以下是函数更改后的全貌:
void OutPutMsgToConsle(ConSleLevel level,const QString &strText)
{
//日志等级大于配置文件允许的最高等级,就返回
//可以用于消息弹出时中止此函数
// if (level > LocalConfig::GetInstance().GetCfgConsleLevel())
// {
// return;
// }
exportMessage->append(strText);
//选中需要显示颜色的文字
QTextCursor cursor = exportMessage->textCursor();
cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor,1);//新增
cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor,1);//新增
QTextCharFormat fmt;
//根据不同等级绘制不同颜色
// QPainter p(exportMessage);
switch (level)
{
case Critical_INFO:
fmt.setForeground(Qt::red);
break;
case Warning_INFO:
fmt.setForeground(QColor(255 ,193 ,37));//黄色
break;
case Running_INFO:
fmt.setForeground(Qt::green);
break;
case Information_INFO:
fmt.setForeground(Qt::black);
break;
default:
break;
}
cursor.mergeCharFormat(fmt);
cursor.clearSelection(); //撤销选中
cursor.movePosition(QTextCursor::EndOfBlock); //cursor和anchor均移至末尾
}
程序效果图: