QTextEdit with different text colors (Qt / C++)

后端 未结 6 846
Happy的楠姐
Happy的楠姐 2020-12-05 18:00

I have a QTextEdit box that displays text, and I\'d like to be able to set the text color for different lines of text in the same QTextEdit box. (i

6条回答
  •  独厮守ぢ
    2020-12-05 18:28

    Extending on https://stackoverflow.com/a/13287446/1619432:

    QTextEdit::append() inserts a new paragraph with the previously set FontWeight / TextColor. insertHTML() or InsertPlainText() to avoid inserting a new paragraph (e.g. to achieve different formats in a single line) do not respect the font/color settings.

    Instead use QTextCursor:

    ...
    // textEdit->moveCursor( QTextCursor::End );
    QTextCursor cursor( textEdit->textCursor() );
    
    QTextCharFormat format;
    format.setFontWeight( QFont::DemiBold );
    format.setForeground( QBrush( QColor( "black" ) ) );
    cursor.setCharFormat( format );
    
    cursor.insertText( "Hello world!" );
    ...
    

提交回复
热议问题