簡體   English   中英

在 QLineEdit 中更改占位符文本的顏色

[英]Change color of placeholder text in QLineEdit

當我使用QLineEdit::setPlaceholderText()設置占位符文本時,它顯示為灰色。

在此處輸入圖片說明

有沒有辦法將顏色更改為其他顏色,例如紅色?

您必須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;
};

還有一個有點hacky但簡單可靠的方式。

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
    }
}

你也可以用這種方式從QLineEdit類派生

你不能 ,至少使用當前的QLineEdit代碼。

從源代碼中可以看出,占位符文本只是簡單地獲取調色板的前景畫筆並使其部分透明,請參閱QLineEdit::paintEvent

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);
    }
}

但是,您可以將上游工作轉換為更通用的解決方案。 特別是我希望將顏色添加到調色板中,或者通常由當前QStyle (例如作為樣式提示 )。

如果要更改QLineEdit占位符文本顏色,則必須自定義組件的QPalette對象。

QPalette p = lineEdit->palette();
p.setColor(QPalette::Mid, Qt::red); // assuming Mid is the color you want to change.
lineEdit->setPalette(p);

我不記得究竟哪個QPalette::ColorRole適合更改QLineEdit的占位符文本顏色。

如果您想使用QSS而不是QPalette,請嘗試以下操作:

setStyleSheet("QLineEdit{"
              "    color: red;" //TEXT COLOR
              "}"
              "QLineEdit[text=\"\"]{"
              "    color: gray;" //TEXTHOLDER COLOR
              "}");
connect(ui->lineEdit, &QLineEdit::textChanged, [=]{ style()->polish(ui->lineEdit); });

您可以更改顏色,但請記住,源代碼中的占位符設置了alpha因子(如另一條評論中所述),無法刪除。 因此,您將始終看到占位符較暗(使用此選項不可能出現白色)。

考慮到Qt給占位符顏色與文本相同的情況,@ Meefte解決方案非常好,除了它增加了50%的不透明度。 因此,幾乎沒有選擇將占位符顏色設置為與文本不同。 但是,即使是這個解決方案也可以通過確保您不需要設置其他變量而不是Qt為您提供的默認變量來改進。

當你有許多QLineEdit控件已被提升為某些控件覆蓋QLineEdit行為,並且placeholderText()已經通過代碼或通過Qt Creator設置時,可能會出現使用默認placeholderText()的需要,即它將是一個引入另一個動態屬性有點痛苦。 但是,如果您沒有促進某些兒童控制,那么為了使用這種解決方案,這樣做是必要的。

class CustomColorPlaceholderLineEdit : public QLineEdit
{
public:
    CustomColorPlaceholderLineEdit(QWidget * parent = 0) : QLineEdit(parent) { color = QColor(0,0,0,128); }

    const QString &customPlaceholderText() const { return mText; }

    void setCustomPlaceholderColor(const QColor &color) { this->color = color; }

    const QColor &customPlaceholderColor() const { return color; }

    void paintEvent(QPaintEvent *event)
    {
        if(color.isValid() && text().isEmpty() && (!placeholderText().isEmpty() || !mText.isEmpty()))
        {
            if(!placeholderText().isEmpty())
            {
                // In this way, placeholderText() is taken into local variable 'mText' care. Whenever placeholderText() will change, there it will be taken care of.
                mText = placeholderText();

                // This will ensure Qt will not draw placeholder for us.
                setPlaceholderText("");
            }

            // By this, we make sure Qt will paint QLineEdit default parts properly.
            QLineEdit::paintEvent(e);

            // And now @Meefte code is reused here.
            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);
            return; // No need to paint again.
        }

        // Default Qt's painting behavior for QLineEdit.
        QLineEdit::paintEvent(e);
    }
private:
    QString mText;
    QColor color;
};

QT還是有這個問題)我是這樣解決的:

bool CustomLineEdit::event(QEvent *event)
{
    bool eventResult = QLineEdit::event(event);

    if (event->type() == QEvent::StyleChange) {
         QPalette pal = palette();
         pal.setColor(QPalette::PlaceholderText, Qt::red);
        setPalette(pal);
    }
    return eventResult;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM