How to change a Button colour



  • Hello guys,

    I searched everywhere for the answer to this question. But the answers I found are either too confusing or don't work. I want a single serial code to change the color of a button while the window is running.

    I have an OpenGL application, and I want the colour to be taken from a QColorDialog and then colour the background of my OpenGL scene, and meanwhile colour the button to show the user what colour chosen (I think you know what I mean).

    Here's the code I'm currently using. The code colours the background behind the button. I want the button itself to be coloured or to have a small section coloured inside it, like we see in all painting programs.

    @
    QPushButton *backgroundColourButton;
    QColor *backgroundColour;
    backgroundColour->setRgb(0,0,0); //example colour, I could later manage to utilize this variable with a QColorDialog
    QPalette Pal(palette());
    Pal.setColor(QPalette::Button, backgroundColour->rgb());
    backgroundColourButton->setAutoFillBackground(true);
    backgroundColourButton->setPalette(Pal);
    @

    Thank you for any efforts :)



  • Easiest way would be to use a style sheet on the button:

    @
    backgroundColourButton->setStyleSheet("background-color: red");
    @

    BTW - according to a "talk of Girish Ramakrishnan":/videos/watch/styling_qt_widgets_using_style_sheets (one of the original developers of Qt widget style sheets) at DevDays 2006, it was exactly the need of "making a red push button" that led to the introduction of Qt style sheets eventually :-)



  • But is it possible to get the colour as string from a QColor object? this would solve my problem!



  • Of course:

    @
    QColor col = QColorDialog::getColor(Qt::white, this);
    if(col.isValid()) {
    QString qss = QString("background-color: %1").arg(col.name());
    ui->pushButton->setStyleSheet(qss);
    }
    @

    Although, the style of the button changes for me, i.e. the rounded box on the Mac is replaced by a plain rectangle.



  • Thanks a lot :-)



  • No prob, you're welcome!



  • @goetz said:

    backgroundColourButton

    como cambio el color de un button al darle click?


  • Qt Champions 2016

    @Pipevasquez2
    Hi This is english section, but guessing from google translate

    QPushButton:pressed {
    background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #0d5ca6, stop: 1 #2198c0);
    }


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.