c++ - 在 QLineEdit 中更改占位符文本的颜色

标签 c++ qt qlineedit

当我使用 QLineEdit::setPlaceholderText() 设置占位符文本时,它显示为灰色。

enter image description here

有什么方法可以将颜色更改为其他颜色,例如红色?

最佳答案

您必须继承 QLineEdit 并在 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;
};

关于c++ - 在 QLineEdit 中更改占位符文本的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27224211/

相关文章:

java - JNA 从 DLL 调用 C++ 对象 - java.lang.IllegalArgumentException : Structure class has unknown or zero size

c++ - Qt 多页 TIFF

c++ - Qt (C++) : Add background text in line edit

c++ - OpenGL - 在一个函数中加载多个纹理

c++ - 跳过 C++ 中的置换元素

c++ - Qt如何通过QPrinter打印QFile?

c++ - Qt C++ 如何将加密文本的 QByteArray 保存到文件中,然后读取并格式化为 QByteArray

c++ - 在 QtWebEngine 中处理下载

Python Qt QLineEdit 奇怪的编码

c++ - 显示 QMessageBox 时如何防止双槽调用?