首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >文本颜色QPlainTextEdit QT

文本颜色QPlainTextEdit QT
EN

Stack Overflow用户
提问于 2019-07-11 19:35:09
回答 1查看 3K关注 0票数 1

我有课

代码语言:javascript
复制
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);
   }
};

和:

代码语言:javascript
复制
plainTextEditor *mainText = new plainTextEditor(centralWidget);

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

代码语言:javascript
复制
ui->mainText->setTextColor(Qt::red);

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

代码语言:javascript
复制
connect(ui->mainText, &QPlainTextEdit::textChanged, [this](){
   ui->mainText->setTextColor(Qt::red);
};

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-11 22:53:50

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

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

代码语言:javascript
复制
QPlainTextEdit *edit = new QPlainTextEdit(this);

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

edit->appendPlainText("HELLO!");

编辑:而不使用StyleSheet:

代码语言:javascript
复制
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!");
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56996185

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档