Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change color of placeholder text in QLineEdit

Tags:

c++

qt

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?

like image 290
Programming Avatar asked Dec 01 '22 01:12

Programming


2 Answers

You'll have to subclass QLineEdit and paint your own placeholder in the paintEvent().

class CustomColorPlaceholderLineEdit : public QLineEdit
{
public:
    CustomColorPlaceholderLineEdit(QWidget * parent = 0) : QLineEdit(parent) { color = QColor(0,0,0,128); }
    void setCustomPlaceholderText(const QString &text) { this->mText = text; }
    const QString &customPlaceholderText() const { return mText; }
    void setCustomPlaceholderColor(const QColor &color) { this->color = color; }
    const QColor &customPlaceholderColor() const { return color; }
    void paintEvent(QPaintEvent *event) {
        QLineEdit::paintEvent(event);
        if (!hasFocus() && text().isEmpty() && !mText.isEmpty()) {
            // QLineEdit's own placeholder clashes with ours.
            Q_ASSERT(placeholderText().isEmpty());
            QPainter p(this);
            p.setPen(color);
            QFontMetrics fm = fontMetrics();
            int minLB = qMax(0, -fm.minLeftBearing());
            QRect lineRect = this->rect();
            QRect ph = lineRect.adjusted(minLB + 3, 0, 0, 0);
            QString elidedText = fm.elidedText(mText, Qt::ElideRight, ph.width());
            p.drawText(ph, Qt::AlignVCenter, elidedText);
        }
    }
private:
    QString mText;
    QColor color;
};
like image 180
Meefte Avatar answered Dec 05 '22 10:12

Meefte


There is another a bit hacky but simple and reliable way.

connect(lineEdit, &QLineEdit::textChanged, this, &YourClass::updateLineEditStyleSheet);

void YourLineEdit::updateLineEditStyleSheet()
{
    if (lineEdit->text().isEmpty()) {
        lineEdit->setStyleSheet("#lineEdit { color: lightGray;"); // Set your color but remember that Qt will reduce alpha
    } else {
        lineEdit->setStyleSheet("#lineEdit { color: black;"); // usual color
    }
}

also you can use this way to derived from QLineEdit class

like image 21
Vernat Khisamov Avatar answered Dec 05 '22 10:12

Vernat Khisamov