PDA

View Full Version : How to change the text color in QPlainTextEditor?



TheIndependentAquarius
5th September 2020, 07:59
void writeToEditor( QString partOfText, double readBytes )
{
QString newFormat;
for( int i = 0; i < readBytes; i = i + 10 )
{
QStringRef subString( &partOfText, i, 10 );
newFormat.append( subString );
newFormat.append( " " );
}

objQPlainTextEdit.appendPlainText( newFormat );

}

Here objQPlainTextEdit is an object of QPlainTextEdit.

Considering: https://doc.qt.io/qt-5/qplaintextedit.html


Each character within a paragraph has its own attributes, for example, font and color.

I can see there is QPalette. How to use it to color the alphabets displayed in QPlainTextEdit, differently?

For example: 'A' should be of red color, and 'B' should be of green colour.

ChristianEhrlicher
5th September 2020, 08:17
See https://doc.qt.io/qt-5/qplaintextedit.html#setCurrentCharFormat

TheIndependentAquarius
5th September 2020, 11:45
I solved it.

Here is the working code:


QString combineHtml = "<p>";

for( int j = 0; j < readBytes; j++)
{
if( partOfText[j] == 'A' )
{
combineHtml.append( QString( "<span style = 'color: red'>")
+ QString( partOfText[j]) + QString( "</span>"));
}
else
{
combineHtml.append( QString( "<span style = 'color: blue'>")
+ QString( partOfText[j]) + QString( "</span>"));
}
}

combineHtml.append( "</p>");

std::cout << combineHtml.toStdString();

objQPlainTextEdit.appendHtml( combineHtml );


Here partOfText is QString, and objQPlainTextEdit is an object of QPlainTextEdit.

Output generated by the above code is as follows:


<p><span style = 'color: blue'>C</span><span style = 'color: red'>A</span><span style = 'color: red'>A</span><span style = 'color: blue'>T</span><span style = 'color: blue'>C</span><span style = 'color: blue'>T</span><span style = 'color: blue'>C</span><span style = 'color: blue'>C</span><span style = 'color: red'>A</span><span style = 'color: blue'>T</span></p>]

13536