简体   繁体   中英

How can I change color of part of the text in QLineEdit?

I want to add some syntax highlighting to text being written in QLineEdit, but it does not support rich text formatting, I can not change QlineEdit to something else, so I should find how to set color of text in this widget.

Is there a way to do this?

Just found a neat trick for that.

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

You can change the color with the use of 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}"); 

You may want to consider using QTextBrowser for this case.

You can change color of texts like this:

QLineEdit *line = new QLineEdit();
line->setText("this is a test");
line->setStyleSheet("foreground-color: blue;");

If it won't work, replace the last line with the following:

line->setStyleSheet("color: blue;");

I was able to accomplish this by overlaying a QLabel on top of a QLineEdit then making the text color of the line edit white. When the textEdited signal is emitted, use it to update the text of the QLabel . The QLabel accepts rich text so you can process the text in the QLineEdit and replace key words with the HTML needed to display the text in the way you want it. I'm sure you could modify the code to change the text color of the current selection.

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)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM