Qt用边框绘制一个填充的圆角矩形 [英] Qt drawing a filled rounded rectangle with border

查看:10728
本文介绍了Qt用边框绘制一个填充的圆角矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要绘制一个带有圆角的矩形(边框半径与所有四个角相同),其中特定颜色填充整个矩形,以及单独的边框颜色(例如边框宽度为1像素)。



从我的观察,Qt提供了三个方法 - fillRect drawRect drawRoundedRect 。我试过他们,他们不工作,因为我想。没有像 fillRoundedRect 的方法。这意味着我可以绘制一个圆角矩形,但它不会填充我想要的颜色。



我该怎么做?而且,我读到,由于一些混叠问题,角落通常是相等的。如何将它设置为相等的所有四个? painter.setRenderHint(QPainter :: Antialiasing)足够了吗?

解决方案

您可以创建一个 QPainterPath ,将圆角矩形添加到它,然后填充和描边:

  QPainter p 
p.setRenderHint(QPainter :: Antialiasing);
QPainterPath path;
path.addRoundedRect(QRectF(10,10,100,50),10,10);
QPen pen(Qt :: black,10);
p.setPen(pen);
p.fillPath(path,Qt :: red);
p.drawPath(path);请注意,即使使用抗锯齿,1像素边框可能永远不会真的看起来不错,特别是在低DPI的情况下桌面显示器,在高DPI移动设备上几乎不可见。





如果您创建矩形为 QRectF(9.5,9.5,100,50)它将看起来更好与1像素的抗锯齿边框,因为它会捕捉在正确的像素:




I want to draw a rectangle with rounded corners (border radius same for all 4 corners) with a specific color filling the entire rectangle, and a separate border color (say border is 1 px wide).

From my observation, Qt provides three methods - fillRect and drawRect and drawRoundedRect. I have tried them, they don't work like I want to. There is no method like fillRoundedRect. Which means that I can draw a rounded rectangle but it won't be filled with the color I want.

How do I do it? And also, I read that due to some aliasing problems, the corners are often rendered equal. How do I set it as equal for all four? Will painter.setRenderHint(QPainter::Antialiasing) suffice? Or do I have to do anything else?

解决方案

You can create a QPainterPath, add the rounded rect to it, and then fill and stroke it:

QPainter p(this);
p.setRenderHint(QPainter::Antialiasing);
QPainterPath path;
path.addRoundedRect(QRectF(10, 10, 100, 50), 10, 10);
QPen pen(Qt::black, 10);
p.setPen(pen);
p.fillPath(path, Qt::red);
p.drawPath(path);

Note that even with antialiasing, 1 px border will probably never really look good, especially on a low DPI desktop monitor, on a high DPI mobile device it will be almost invisible.

If you create the rectangle as QRectF(9.5, 9.5, 100, 50) it will look better with 1 px antialiased border, because it will "snap" on the right pixel:

这篇关于Qt用边框绘制一个填充的圆角矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆