Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 文本颜色QPlainTextEdit QT_C++_Qt_Qt5 - Fatal编程技术网

C++ 文本颜色QPlainTextEdit QT

C++ 文本颜色QPlainTextEdit QT,c++,qt,qt5,C++,Qt,Qt5,我有课 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))

我有课

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);
   }
};
以及:

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

ui->mainText->setTextColor(Qt::red);
但如果我删除所有文本并再次写入,文本颜色将返回黑色。 我尝试修复:

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

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

如果您的目标是简单地设置所有文本的颜色,那么您可以使用Qt样式表

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

QPlainTextEdit *edit = new QPlainTextEdit(this);

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

edit->appendPlainText("HELLO!");
编辑:不使用样式表:

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!");

我不能使用样式表我不能使用编辑->追加HTML

+纯文本+

@跳过:这是一个HTML特性,在我的编辑中用as环绕文本。
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!");