c++qtqcolor

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


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.


Solution

  • 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.