使用QTextEdit实现状态信息显示框

使用QTextEdit实现状态信息显示框:

1,  使用QTextTable,组织状态信息

2,  当状态信息达到一定量时,自动删最早的一条记录。(为这个 查了好久QTextEdit删除内容的方法才实现这功能, 所以留下这篇记录,以备再用。)

void MainWindow::onStatusInfo(int flag,QString msg)
{
    QString text;
    QTextCharFormat chfmt;
    //设置状态信息标签
    switch (flag) {
    case 1:
        text = "INFO";
        chfmt.setForeground(QBrush(Qt::black));
        break;
    case 2:
        text = "WARN";
        chfmt.setForeground(QBrush(Qt::yellow));
        break;
    case 3:
        text = "ERROR";
        chfmt.setForeground(QBrush(Qt::red));
        break;
    default:
        break;
    }
    //在标签之后附加状态信息
    text.append(" "+msg);
    //将插入位置设置到QTextEdit最后一行
    QTextCursor cur = ui->statusTextEditer->textCursor();
    cur.movePosition(QTextCursor::End);
    QTextTabelFormate tableformate;
    tableformate.setBorder(0);
    //插入table,用于显示状态信息
    QTextTable *table = cur.insertTable(2,1,tableformate);
    table->cellAt(0,0).firstCursorPosition().insertText("["+QTime::currentTime().toString("hh:mm:ss")+"]");
    table->cellAt(1,0).firstCursorPosition().insertText(text);
    cur.movePosition(QTextCursor::EndOfBlock,QTextCursor::KeepAnchor,1);
    cur.select(QTextCursor::BlockUnderCursor);
    cur.mergeCharFormat(chfmt);
    cur.clearSelection();
    QScrollBar *bar = ui->statusTextEdit->verticalScrollBar();
    bar->setValue(bar->maximum());
    //状态信息条数+1
    m_status_count ++;
    //如果信息数>50,则删除最早的一条记录
    if(m_status_count >50)
    {
        //将选择光标移至第一个字符
        cur.setPosition(1,QTextCursor::MoveAnchor);
        //选择最早含有最早状态信息的table
        cur.movePosition(QTextCursor::EndOfBlock,QTextCursor::KeepAnchor,1);
        cur.select(QTextCursor::BlockUnderCursor);
        //删除该信息
        cur.removeSelectedText();
        //光标移至QTextEdit末行
        cur.movePosition(QTextCursor::End,QTextCursor::MoveAnchor);
        m_status_count --;
    }

}


你可能感兴趣的:(QT)