Search code examples
c++qtqlineeditqtwidgets

Custom placeholder in QLineEdit


I want to have a QLineEdit with the specific placeholder text format: it needs to have left aligned and right aligned text. Here is an example:

example

Any ideas?


Solution

  • Unfortunately, this seems to be all hard coded in void QLineEdit::paintEvent(QPaintEvent *) as follows:

    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 could reimplement this on your own in a subclass if you wish.

    Naturally, you could also "cheat" with space and font sizes, but that would require a bit more work, and would be nastier in the end, too, let alone long-term reliability.

    You could also contribute to the Qt Project to make this class more flexible, but they could reject it with the reason of not being common case enough. It is up to the maintainer(s).