gpt4 book ai didi

c++ - 在QT中为QPainter设置填充颜色(不是描边颜色)

转载 作者:行者123 更新时间:2023-11-30 05:00:10 24 4
gpt4 key购买 nike

如何在 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);

工作。但事实并非如此。我做错了什么?

调试后发现 setBrush 方法根本没有更新画笔颜色: enter image description here

颜色 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();
}

enter image description here

关于c++ - 在QT中为QPainter设置填充颜色(不是描边颜色),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50900565/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com