Qt绘制带边框的填充圆角矩形

时间:2023-02-10 00:00:08

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).

我想画一个圆角的矩形(所有4个角的边框半径相同),特定的颜色填充整个矩形,并且有一个单独的边框颜色(比如边框宽1 px)。

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.

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

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

我该怎么做?而且,我读到由于一些混叠问题,角落经常被渲染为不相等。如何将它设置为全部四个相等?请问painter.setRenderHint(QPainter :: Antialiasing)是否足够?或者我还需要做其他事情吗?

1 个解决方案

#1


38  

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

您可以创建QPainterPath,向其添加圆角矩形,然后填充并描边:

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.

请注意,即使使用抗锯齿功能,1 px边框也可能永远不会看起来很好,特别是在低DPI桌面显示器上,在高DPI移动设备上,它几乎不可见。

Qt绘制带边框的填充圆角矩形

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:

如果您将矩形创建为QRectF(9.5,9.5,100,50),使用1 px抗锯齿边框会更好看,因为它会在右侧像素上“捕捉”:

Qt绘制带边框的填充圆角矩形

#1


38  

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

您可以创建QPainterPath,向其添加圆角矩形,然后填充并描边:

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.

请注意,即使使用抗锯齿功能,1 px边框也可能永远不会看起来很好,特别是在低DPI桌面显示器上,在高DPI移动设备上,它几乎不可见。

Qt绘制带边框的填充圆角矩形

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:

如果您将矩形创建为QRectF(9.5,9.5,100,50),使用1 px抗锯齿边框会更好看,因为它会在右侧像素上“捕捉”:

Qt绘制带边框的填充圆角矩形