功能描述: 修改QLineEdit中部分文本的样式
预期效果:
windows系统路径不允许有?
等符号,高亮显示不允许的符号。
[toc]
实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| 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>()); }
|
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| 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);
|