其他分享
首页 > 其他分享> > QTextEdit调用append函数时自动换行问题

QTextEdit调用append函数时自动换行问题

作者:互联网

QTextEdit可通过append函数向文本框内追加字符,但每没次追加都会使光标移动到下一行,下面将介绍一种方法追加字符时不需要换行:

//往界面上添加展示的消息
void DataMonitorWidget::appendData(QString data)
{
    //获取滚动条位置
    bool atEnd = ui.textEdit->verticalScrollBar()->value() >= ui.textEdit->verticalScrollBar()->maximum();
    QTextCharFormat fmt;
    //fmt.setForeground(color);

    QTextCursor tmp(ui.textEdit->document());

    tmp.beginEditBlock();
    tmp.movePosition(QTextCursor::End);

    if (!ui.textEdit->document()->isEmpty())
    {
        tmp.insertBlock(ui.textEdit->textCursor().blockFormat(), ui.textEdit->textCursor().charFormat());
    }
    else {

        tmp.setCharFormat(ui.textEdit->textCursor().charFormat());
    }

    tmp.movePosition(QTextCursor::End);
    tmp.deletePreviousChar();

    tmp.insertText(data, fmt);

    // preserve the char format
    QTextCharFormat oldCharFormat = ui.textEdit->textCursor().charFormat();

    if (!ui.textEdit->textCursor().hasSelection())
        ui.textEdit->textCursor().setCharFormat(oldCharFormat);

    tmp.endEditBlock();
    if (atEnd)
        ui.textEdit->verticalScrollBar()->setValue(ui.textEdit->verticalScrollBar()->maximum());

}

 

标签:tmp,换行,QTextEdit,textCursor,textEdit,ui,verticalScrollBar,QTextCursor,append
来源: https://www.cnblogs.com/aoxian/p/15912752.html