Colorful text in the same line in TRichEdit
Asked Answered
T

3

13

How to write text in the same line but with different color? (I use richedit).

procedure TForm1.btnEClick(sender: TObject);
begin

  m0.SelAttributes.Color := clBlue;
  m0.SelAttributes.Style := [fsBold];
  m0.lines.add('This is blue and it is bold');
  m0.SelAttributes.Color := clGreen;
  m0.SelAttributes.Style := [fsBold];
  m0.lines.add ('This is Green and it is bold');
  m0.lines.add('');
  m0.lines.add('But how to write text in the same line with different color?');
  // i want to have both blue and green in the same line 
end;

Best Wishes, Bee

Tuft answered 25/11, 2013 at 5:18 Comment(0)
P
33

You're on the right track. Just change SelAttributes and use SelText instead of Lines.Add:

procedure TForm4.FormCreate(Sender: TObject);
begin
  RichEdit1.Clear;
  RichEdit1.SelAttributes.Color := clBlue;
  RichEdit1.SelAttributes.Style := [fsBold];
  RichEdit1.SelText := 'This is bold blue text.';
  RichEdit1.SelAttributes.Color := clRed;
  RichEdit1.SelAttributes.Style := [fsItalic];
  RichEdit1.SelText := #32'This is italic red text';
end;

This produces

Sample output from code above

Prouty answered 25/11, 2013 at 6:24 Comment(0)
L
3

if you are using themes... answer above won't work..
you cannot see any colors... till you remove seFont from styles..

RichEdit1.styleElements:=richedit1.styleElements-[seFont];

eg.

....
amsg:='Hola';

RichEdit1.SelStart := RichEdit1.GetTextLen();
RichEdit1.SelAttributes.Color := acolor;
RichEdit1.Lines.Add(amsg + sLineBreak);
RichEdit1.SelLength := Length(amsg + sLineBreak);
Lorusso answered 18/6, 2020 at 22:14 Comment(1)
Small nitpick: you should change Length(RichEdit1.Lines.Text) to RichEdit1.GetTextLen(), no need to waste memory retrieving the actual Text as a string just to get its length, when the TRichEdit already knows that info internally.Arnoldoarnon
N
1

For the last piece of text in the line, include a carriage return to finish off the line.

RichEdit1.SelAttributes.Color := clGreen;
RichEdit1.SelAttributes.Style := [];
RichEdit1.SelText := 'This is the last piece of text on the line.' + #13;
Noellenoellyn answered 27/8, 2019 at 8:27 Comment(3)
I don't think this answers the OP's question. (Ken White probably did answer the intended question.)Regionalism
Yes. Ken's answer is correct. I should have added my answer as a comment as it is more a (hopefully) helpful tip rather than an answer. (I don't have enough reputation points to add comments.)Noellenoellyn
OK, fair enough! :)Regionalism

© 2022 - 2024 — McMap. All rights reserved.