c++ - 文字颜色 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!");
编辑:不使用样式表:
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!");
推荐阅读
- python - 用于获取 redfin 估计值的 Redfin 刮板
- r - 如何使用ggplot将两个不同比例的y轴放在绘图的同一侧?
- python - 哪种方法更快?
- html - SVG 对象最初是垂直加载的,然后在浏览器中水平重新排列
- mysql - 我的 SQL 请求不会在 localhost 和 prod 中返回相同的内容
- sql - 需要表结构来存储html标签并存储和返回它的值
- list - 在 Haskell 中使用分隔字符将字符串划分为更多部分
- geolocation - 有没有办法在 Facebook 的 Spark AR 中访问地理位置数据?
- c# - Azure DevOps 中无法识别 Microsoft Enterprise Library
- docker - 我可以将 docker fluentd 日志驱动程序配置为直接连接到容器吗?