C++ Qt绘制一个带边框的填充圆角矩形
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29196610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Qt drawing a filled rounded rectangle with border
提问by SexyBeast
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 像素)。
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
anddrawRect
和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)
足够?还是我必须做其他事情?
回答by dtech
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 像素边框也可能永远不会真正好看,尤其是在低 DPI 桌面显示器上,在高 DPI 移动设备上它几乎不可见。
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 抗锯齿边框看起来更好,因为它会“捕捉”在正确的像素上: