Qt How to create a QBrush using a RGB Color with QColor and change it later?

26.5k Views Asked by At

At the moment I use this to create a QBrush:

QBrush *goldBrush = new QBrush(QColor(212,175,55));
scene->addRect(0,415,20,50,noPen,*goldBrush);

But apparently this leaks memory.

How else could you do it? I've tried this:

QBrush greyBrush(QColor(212,175,55));
greyBrush.setColour(QColor(120,60,55))

But that hasn't worked either. I want to be able to declare the brush as one colour then be able to change it.

Edit: full problem my bad.

2

There are 2 best solutions below

2
On BEST ANSWER

The only way to change the color of a brush is via QBrush::setColor. The brush takes a copy of the color you specify and not a reference.

QBrush my_brush;
QColor red(Qt::red);
my_brush.setColor(red); // my_brush has its own color member internally
                        // and _not_ a reference to red

Maybe you are used to other programming languages like Java where basically everything is a reference. In C++ there are values semantics.

1
On

Don't forget to set the brush style

QPainter painter(this);
QBrush brush;
QColor brushColor;
brushColor.setRgb(192 ,237, 166);
brush.setColor(brushColor);
brush.setStyle(Qt::SolidPattern);