Search code examples
c++qtqlineedit

Change color of placeholder text in QLineEdit


When I set the placeholder text with QLineEdit::setPlaceholderText(), it appears gray.

enter image description here

Is there any way to change the color to something else, for example red?


Solution

  • You can't, at least with the current QLineEdit code.

    As you can see from the source code, the placeholder text is simply taking the foreground brush of the palette and making it partially transparent, see QLineEdit::paintEvent:

    if (d->shouldShowPlaceholderText()) {
        if (!d->placeholderText.isEmpty()) {
            QColor col = pal.text().color();
            col.setAlpha(128);
            QPen oldpen = p.pen();
            p.setPen(col);
            QRect ph = lineRect.adjusted(minLB, 0, 0, 0);
            QString elidedText = fm.elidedText(d->placeholderText, Qt::ElideRight, ph.width());
            p.drawText(ph, va, elidedText);
            p.setPen(oldpen);
        }
    }
    

    You can work with upstream into a more general solution, though. In particular I one would expect that color to be added to the palette, or in general provided by the current QStyle (for instance as a style hint).