繁体   English   中英

文字颜色QPlainTextEdit QT

[英]text color QPlainTextEdit QT

我有课

class plainTextEditor: public QPlainTextEdit
{
    Q_OBJECT
public:
   void setTextColor(const QColor &c); // default function setTextColor(const QColor &c) from QTextEdit
   {
      QTextCharFormat fmt;
      fmt.setForeground(QBrush(c));
      this->mergeCurrentCharFormat(fmt);
   }
};

和:

plainTextEditor *mainText = new plainTextEditor(centralWidget);

我在启动窗口构造函数中使用以下代码:

ui->mainText->setTextColor(Qt::red);

但是,如果我删除所有文本并再次写入,则文本颜色将恢复为黑色。 我尝试修复:

connect(ui->mainText, &QPlainTextEdit::textChanged, [this](){
   ui->mainText->setTextColor(Qt::red);
};

但是,如果我选择所有文本并粘贴,则文本颜色部分为黑色

如果您的目标只是设置所有文本的颜色,则可以使用Qt StyleSheet!

下面的示例将背景色更改为黑色,将文本颜色更改为红色:

QPlainTextEdit *edit = new QPlainTextEdit(this);

//StyleSheet here
edit->setStyleSheet("QPlainTextEdit {background-color: black; color: red;}");

edit->appendPlainText("HELLO!");

编辑:不使用StyleSheet:

QPlainTextEdit *edit = new QPlainTextEdit(this);

//Here we are using the HTML capabilities of Qt
//Converting the string using toHtmlEscaped to allow html special characters to be displayed
//Using blockSignals to not generate loop on text manipulation
//Using <pre> tag to allow multiple spaces

connect(edit, &QPlainTextEdit::textChanged, this, [=]{
    const QString plainText = edit->toPlainText().toHtmlEscaped();

    edit->blockSignals(true);
    edit->clear();
    edit->appendHtml("<p style=\"color:red;white-space:pre\">" + plainText + "</p>"
    edit->blockSignals(false);
});

edit->appendPlainText("HELLO!");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM