为什么QPainter绘图无效?

235 篇文章 175 订阅

#include "MyBtnLayout.h"
#include <QtWidgets/QApplication>
#include "QFile"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QFile file(":/MyBtnLayout/dispaly.css");
    file.open(QFile::ReadOnly);
    if (file.isOpen())
    {
        QString styleSheet = QLatin1String(file.readAll());
        a.setStyleSheet(styleSheet);
    }
    file.close();

    MyBtnLayout w;
    w.show();
    return a.exec();
}





//下面是重写的paintEvent函数
void MyBtnLayout::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setPen(QPen(Qt::red));
    painter.setBrush(QBrush(Qt::blue));
    //painter.drawRect(ui.widget->rect());
    painter.drawRect(0,0,50,50);
    //painter.drawLine(rect().width(),0,width(),height());
}

可以看到paintEvent中的代码非常简单,只是画个矩形而已,但是程序运行起来之后,却没有效果。其实这里是因为在main函数中对整个应用程序加载了样式表导致的,在样式表文件中,我把整个应用程序的背景设置为白色的了,导致paintEvent画不出来矩形,这里应该是画出了矩形,但之后又被样式表中设置的背景给覆盖掉了。

如何解决?

1.不使用样式表

2.只对部分控件设置样式表,不要在我们重绘的区域设置样式

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
如果您使用`QSvgRenderer`和`QPainter`来绘制SVG文件,但设置颜色没有效果,可能是因为SVG文件中的某些元素使用了硬编码的颜色。在这种情况下,渲染器会忽略任何颜色设置,因为SVG文件中的颜色比渲染器中指定的颜色更具体。 要解决这个问题,可以尝试将SVG文件中的颜色替换为可以通过渲染器设置的颜色。例如,您可以使用`QString::replace()`方法将SVG文件中的颜色替换为占位符,然后在渲染器中使用实际的颜色替换占位符。以下是一个示例代码: ```cpp #include <QSvgRenderer> #include <QPainter> void changeSvgColor(const QString &filePath, const QColor &color, QImage &image) { QSvgRenderer renderer(filePath); QPainter painter(&image); // Replace all instances of "red" with the desired color QString svgString = QString(renderer.currentBoundDocument().data()); QString colorString = QString("rgb(%1, %2, %3)").arg(color.red()).arg(color.green()).arg(color.blue()); svgString.replace("red", colorString); // Create a new SVG renderer from the modified SVG string QSvgRenderer newRenderer(svgString.toUtf8()); // Render the modified SVG to the QImage newRenderer.render(&painter); } ``` 在上述代码中,`changeSvgColor()`函数从给定的SVG文件中创建一个`QSvgRenderer`对象,并将SVG文件中的所有“red”字符串替换为指定的颜色。然后,我们使用修改后的SVG字符串创建一个新的`QSvgRenderer`对象,并将其用于渲染图像。 请注意,如果SVG文件中的颜色不是硬编码的,而是使用CSS样式表定义的,则可以使用`QPainter::setRenderHint()`方法启用`QPainter::Antialiasing`标志,以使颜色设置生效。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Allen Roson

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值