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

标签 c++ qt colors qt5 qpainter

如何在 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/

相关文章:

c++ - 不与共享库共享所有类

c++ - 使用 C++ 读取一行数字

c++ - 在原始类型模板特化之间转换

HTML CSS3 - 为什么页脚背景颜色不起作用?

jquery - 我如何使用 jQuery 改变 div 中的背景颜色?

c++ - 我可以验证预处理器宏以确保它是一个数字吗?

c++ - 无法再连接到进程仍在监听的本地端口

c++ - Qt5PrintSupportd.dll 丢失

qt - 如何在不使用 QtCreator 的情况下将 dll 文件复制到 Qt 中的输出目录?

qt - 如何在 Visual Studio 中构建现有的 Qt 项目?