如何在 QT 中为 QPainter
设置填充颜色(不是描边颜色)?
例如,我有一段代码负责填充矩形。看起来像:
painter.fillRect(fillRect, Qt::SolidPattern);
其中painter
的类型是QPainter
。当然,我知道可以将 case 中的颜色指定为第二个参数,但我的程序中有这样的设计,如果我可以设置 painter
会好很多预先填充颜色(默认情况下颜色为黑色)。
我尝试使用 painter.setBackground(Qt::yellow);
,但没有帮助。
嗯。根据this我们有:
Sets the painter's brush to the given brush.
The painter's brush defines how shapes are filled.
所以,我希望是这样的
QRect fillRect;
painter.setBrush(QBrush(Qt::yellow));
painter.fillRect(fillRect, Qt::SolidPattern);
工作。但事实并非如此。我做错了什么?
颜色 rgb
保持不变:(0, 0, 0)。
最佳答案
fillRect()
接受一个 QBrush
作为第二个参数,所以我可以使用它:
painter.fillRect(r, QBrush(Qt::yellow, Qt::SolidPattern));
更新:
#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();
}
关于c++ - 在QT中为QPainter设置填充颜色(不是描边颜色),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50900565/