Gradient color for text of QLabel Qt/c++

Viewed 781

I trying to set gradient color for QLabel text. I am trying to use setStyleSheet function but it doesn't work. I read this article but still can't get the working solution.

this is my code

void MyClass::setTitle(const QString& text)
{
    m_text = text;
    m_titleText->setText(text);
    QFont font = m_titleText->font();
    font.setPointSize(12);
    m_titleText->setFont(font);
    m_titleText->setStyleSheet("color: qlineargradient(x1: 0, y1: 0,    x2: 0, y2: 1,    #3d5afe: 0 #66e, stop: 1 #fd3e7f);")
}

Is there any solution for this problem? Thanks advance.

3 Answers

You can try this.

   void MyClass::setTitle(const QString& text)
    {
        m_text = text;
        m_titleText->setText(text);
        QFont font = m_titleText->font();
        font.setPointSize(12);
        m_titleText->setFont(font);
        QPalette labelPal;
        QLinearGradient colorGradient = QLinearGradient(0, 0, m_titleText->width(), 0);
        colorGradient.setSpread(QGradient::RepeatSpread);
        colorGradient.setColorAt(0, QColor("#3d5afe"));
        colorGradient.setColorAt(1, QColor("#fd3e7f"));
        QBrush brush(colorGradient);
        labelPal.setBrush(QPalette::ColorRole::Text, brush);
    
        m_titleText->setPalette(labelPal);
        m_titleText->setForegroundRole(QPalette::Text);
    }

You're using an invalid syntax, but the QSS parser is not able to determine that (or, at least, doesn't give any warning about it), so it just ignores the gradient and uses the default palette color for text.
The problem is that you're missing a stop definition and used a color instead.

Change to:

    m_titleText->setStyleSheet("color: qlineargradient(x1: 0, y1: 0,    x2: 0, y2: 1,    stop: 0 #66e, stop: 1 #fd3e7f);")

Note that the same could also be done using a QPalette with a QLinearGradient (with object bounding mode) set as brush for the WindowText role.

 ui->label->setStyleSheet(
    "* {color: qlineargradient(spread:pad, x1:0 y1:0, x2:1 y2:0, stop:0 rgba(0, 0, 0, 255), stop:1 rgba(255, 255, 255, 255));"
    "background: qlineargradient( x1:0 y1:0, x2:1 y2:0, stop:0 cyan, stop:1 blue);}");

enter image description here

Related