在TRichEdit中同一行的彩色文本

时间:2013-11-25 05:18:56

标签: delphi fonts richedit

如何在同一行中写入文字但颜色不同? (我使用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;

祝福, 蜂

3 个答案:

答案 0 :(得分:21)

你走在正确的轨道上。只需更改SelAttributes并使用SelText代替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;

这会产生

Sample output from code above

答案 1 :(得分:1)

如果您正在使用主题...上面的答案将不起作用..
你看不到任何颜色... 直到您从样式中删除seFont。.

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

例如

....
amsg:='Hola';

RichEdit1.SelStart := Length(RichEdit1.Lines.Text);
RichEdit1.SelAttributes.Color := acolor;
RichEdit1.Lines.Add(amsg + sLineBreak);
RichEdit1.SelLength := Length(amsg + sLineBreak);

答案 2 :(得分:0)

对于该行的最后一段文字,请包含回车符以结束该行。

RichEdit1.SelAttributes.Color := clGreen;
RichEdit1.SelAttributes.Style := [];
RichEdit1.SelText := 'This is the last piece of text on the line.' + #13;