[英]How can I change color of part of the text in QLineEdit?
我想為在 QLineEdit 中編寫的文本添加一些語法突出顯示,但它不支持富文本格式,我無法將 QlineEdit 更改為其他內容,因此我應該找到如何在此小部件中設置文本顏色。
有沒有辦法做到這一點?
剛剛找到了一個巧妙的技巧。
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);
您可以使用樣式表更改顏色。
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
。
你可以改變這樣的文字顏色:
QLineEdit *line = new QLineEdit();
line->setText("this is a test");
line->setStyleSheet("foreground-color: blue;");
如果它不起作用,請用以下內容替換最后一行:
line->setStyleSheet("color: blue;");
我能夠覆蓋一個做到這一點QLabel
上的頂部QLineEdit
,然后拍行編輯白色的文本顏色。 當發出textEdited
信號時,使用它來更新QLabel
的文本。 QLabel
接受富文本,因此您可以處理QLineEdit
中的文本,並用所需的 HTML 替換關鍵字,以按您希望的方式顯示文本。 我確定您可以修改代碼以更改當前選擇的文本顏色。
class LabelEditPair(QLineEdit):
"""
QLineEdit that changes the color of the word 'blue' to blue and
the changes the font weight of the word 'bold' to bold.
"""
def __init__(self):
super().__init__()
self.label = QLabel("starting out")
self.label.setParent(self)
self.label.move(3, 0)
self.label.setAttribute(Qt.WA_TransparentForMouseEvents)
self.setStyleSheet("QLineEdit{color: white}")
self.textEdited.connect(self.text_edited)
def resizeEvent(self, event):
self.label.setFixedHeight(self.height())
self.label.setFixedWidth(self.width())
super().resizeEvent(event)
def text_edited(self, text):
text = text.replace("blue", "<span style='color: blue'>blue</span>")
text = text.replace("bold", "<span style='font-weight: bold'>bold</span>")
self.label.setText(text)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.