Reputation: 407
How could I set the fill color (not the stroke color) for the QPainter
in QT?
For example, I have a code which is responsible for filling the rectangle. It looks like:
painter.fillRect(fillRect, Qt::SolidPattern);
Where the type of painter
is QPainter
. Of course, I know that it is possible to specify the color in the case as a second parameter, but I have such a design in my program that it would be a lot better if I could set the painter
fill color beforehand (by default the color is black).
I tried to use painter.setBackground(Qt::yellow);
, but it did not help.
Hm. According to this we have:
Sets the painter's brush to the given brush.
The painter's brush defines how shapes are filled.
So, I would expect something like
QRect fillRect;
painter.setBrush(QBrush(Qt::yellow));
painter.fillRect(fillRect, Qt::SolidPattern);
to work. But it does not. What am I doing wrong?
After debugging it turns out that the setBrush
method does not update the brush color at all:
The color rgb
stays the same: (0, 0, 0).
Upvotes: 4
Views: 10540
Reputation: 243955
fillRect()
accepts a QBrush
as a second parameter, so I could use it:
painter.fillRect(r, QBrush(Qt::yellow, Qt::SolidPattern));
Update:
#include <QApplication>
#include <QLabel>
#include <QPainter>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QPixmap pixmap(128, 128);
pixmap.fill(Qt::transparent);
QPainter painter(&pixmap);
QRect r= pixmap.rect();
painter.setBrush(QBrush(Qt::yellow));
painter.fillRect(r, painter.brush());
painter.end();
QLabel w;
w.setPixmap(pixmap);
w.show();
return a.exec();
}
Upvotes: 5