qtqtextcursor

QPlainTextEdit: different char format for part of text


after scanning several examples I didn't manage to solve this problem: I created a test for this having a simple MainWindow with a QPlainTextEdit containing some text. On a trigger I want a part of the text to be red and underlined. But that never happens.

Regards

My code:

void MainWindow::on_actionTest_triggered()
{
    QTextCursor cur = ui.plainTextEdit->textCursor();
    cur.setPosition(49);
    QTextCharFormat oldFormat = cur.charFormat();
    QTextCharFormat newFormat = oldFormat;
    newFormat.setForeground(Qt::darkRed);
    newFormat.setUnderlineColor(Qt::darkRed);
    newFormat.setUnderlineStyle(QTextCharFormat::WaveUnderline);
    newFormat.setFontUnderline(true);
    cur.setCharFormat(newFormat);
    cur.setPosition(cur.position()+11);
    cur.setCharFormat(oldFormat);
    ui.plainTextEdit->setTextCursor(cur);
}

using QTextEdit instead doesn't change anything)


Solution

  • This is your solution:

    Using QTextCharFormat to set Underline and background.

    void MainWindow::on_pushButton_clicked()
    {
        int begin = 30;   //begin highlight
        int end = 40;     //end highlight
    
        QTextCharFormat fmt;
        fmt.setBackground(Qt::red); // set color red
        fmt.setUnderlineStyle(QTextCharFormat::SingleUnderline); //set underline
        QTextCursor cursor(ui->plainTextEdit->document());
        cursor.setPosition(begin, QTextCursor::MoveAnchor);
        cursor.setPosition(end, QTextCursor::KeepAnchor);
        cursor.setCharFormat(fmt);
    }
    

    image