цвет текста QPlainTextEdit QT - PullRequest
       26

цвет текста QPlainTextEdit QT

0 голосов
/ 11 июля 2019

У меня есть класс

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);
};

Но если я выделю весь текст и вставлю, цвет текста будет частично черным

1 Ответ

1 голос
/ 12 июля 2019

Если ваша цель - просто установить цвет всего текста, вы можете использовать Qt StyleSheet!

В следующем примере цвет фона меняется на черный, а цвет текста на красный:

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