MPelletier
MPelletier

Reputation: 16657

Colouring a button in Qt

I'm trying to design a simple button (QPushButton or QToolButton, either can work) that would essentially be a rectangle of the colour it represents. Clicking it opens a QColorDialog, and selecting a colour in it repaints the button.

So, basically, something that will look like one of these:

enter image description here

I made a few attempts, none of which brought me the functionality I wanted.

Slot:

void MainWindow::OnButtonColorClick()
{
    QColor initialColor = ui->buttonColor->palette().color(QPalette::Background);

    QColor colorSelected = QColorDialog::getColor(initialColor, this);

    if(colorSelected.isValid())
    {
        ui->buttonColor->setPalette(QPalette(colorSelected));
        ui->buttonColor->setAutoFillBackground(true);
    }
}

Attempt #1:

Set the Palette in the constructor:

ui->buttonCoulor->setPalette(QPalette(Qt::black));

Result: ordinary button before click, thin coloured contour after selection.

enter image description here


Attempt #2:

Add stylesheet:

background-color: rgb(0, 0, 0);

Result: black rectangle before click, black rectangle after selection.

enter image description here


I feel like I'm circling the drain. Essentially, how do I achieve:

enter image description here

?

Upvotes: 0

Views: 10651

Answers (4)

Mikes
Mikes

Reputation: 46

As a follow-up to phyatt's answer, there's a shortcut to generate the XML-formatted color string:

QString s("background: " + color.name + ";");
button->setStyleSheet(s);

Upvotes: 0

cppguy
cppguy

Reputation: 3713

use setStyleSheet with this style sheet:

border: 1px solid black;
background-color: #XXXXXX;

where XXXXXX is the value returned by QString::number(myColor.rgb(), 16).toUpper();

No need to set any other properties on the button. Leave them all as default and this will work.

Upvotes: 1

alwences
alwences

Reputation: 56

This seems to be working just fine for me:

if(colorSelected.isValid())
{
    ui->buttonColor->setPalette(QPalette(colorSelected));
}

Upvotes: 0

phyatt
phyatt

Reputation: 19102

Here is one way to accomplish the desired effect:

// Slot for the button
void MainWindow::on_button()
{
    QColor color = QColorDialog::getColor();

    QString s("background: #"
                          + QString(color.red() < 16? "0" : "") + QString::number(color.red(),16)
                          + QString(color.green() < 16? "0" : "") + QString::number(color.green(),16)
                          + QString(color.blue() < 16? "0" : "") + QString::number(color.blue(),16) + ";");
    button->setStyleSheet(s);
    button->update();
}

Hope that helps.

Upvotes: 3

Related Questions