我想为在QLineEdit中编写的文本添加一些语法高亮,但它不支持富文本格式,我不能将QlineEdit更改为其他内容,所以我应该找到如何设置此小部件中文本的颜色。 / p>
有办法做到这一点吗?
答案 0 :(得分:21)
刚刚找到了一个巧妙的技巧。
static void setLineEditTextFormat(QLineEdit* lineEdit, const QList<QTextLayout::FormatRange>& formats)
{
if(!lineEdit)
return;
QList<QInputMethodEvent::Attribute> attributes;
foreach(const QTextLayout::FormatRange& fr, formats)
{
QInputMethodEvent::AttributeType type = QInputMethodEvent::TextFormat;
int start = fr.start - lineEdit->cursorPosition();
int length = fr.length;
QVariant value = fr.format;
attributes.append(QInputMethodEvent::Attribute(type, start, length, value));
}
QInputMethodEvent event(QString(), attributes);
QCoreApplication::sendEvent(lineEdit, &event);
}
static void clearLineEditTextFormat(QLineEdit* lineEdit)
{
setLineEditTextFormat(lineEdit, QList<QTextLayout::FormatRange>());
}
// Usage example:
QLineEdit* lineEdit = new QLineEdit;
lineEdit->setText(tr("Task Tracker - Entry"));
QList<QTextLayout::FormatRange> formats;
QTextCharFormat f;
f.setFontWeight(QFont::Bold);
QTextLayout::FormatRange fr_task;
fr_task.start = 0;
fr_task.length = 4;
fr_task.format = f;
f.setFontItalic(true);
f.setBackground(Qt::darkYellow);
f.setForeground(Qt::white);
QTextLayout::FormatRange fr_tracker;
fr_tracker.start = 5;
fr_tracker.length = 7;
fr_tracker.format = f;
formats.append(fr_task);
formats.append(fr_tracker);
setLineEditTextFormat(lineEdit, formats);
答案 1 :(得分:2)
您可以使用style sheets更改颜色。
QLineEdit* myLineEdit = new QLineEdit("Whatever");
//for whatever case you want to change the color
if(syntax_needs_to_highlighted)
myLineEdit->setStyleSheet("QLineEdit#myLineEdit{color:blue}");
您可能需要考虑在这种情况下使用QTextBrowser
。
答案 2 :(得分:2)
你可以改变这样的文字颜色:
QLineEdit *line = new QLineEdit();
line->setText("this is a test");
line->setStyleSheet("foreground-color: blue;");
如果不起作用,请用以下内容替换最后一行:
line->setStyleSheet("color: blue;");