When I set the placeholder text with QLineEdit::setPlaceholderText()
, it appears gray.
Is there any way to change the color to something else, for example red?
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;
};
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With