继承自QLineEdit,重写绘制 代码如下: - #ifndef CUSTOMLINEEDIT_H
#define CUSTOMLINEEDIT_H
#include <QObject> #include <QLineEdit> #include <QPainter> #include <QDebug>
class CustomLineedit : public QLineEdit { Q_OBJECT Q_PROPERTY(QColor placeholderColor READ customPlaceholderColor WRITE setCustomPlaceholderColor)
public: explicit CustomLineedit(QWidget *parent = nullptr);
void setCustomPlaceholderText(const QString &text) { this->mText = text; update(); } 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 + 2, 0, 0, 0); QString elidedText = fm.elidedText(mText, Qt::ElideRight, ph.width()); p.drawText(ph, Qt::AlignVCenter, elidedText); } } private: QString mText; QColor color; };
#endif // CUSTOMLINEEDIT_H
主要来自于 Stack Overflow
|