[英]Rounded icon on Qpushbutton
I have a QPushButton
to which I want to add an icon (that I add to the button by using QPushButton::setIcon()
) with rounded corners. 我有一个
QPushButton
要向其中添加带有圆角的图标(使用QPushButton::setIcon()
将其添加到按钮)。 However I have a pixmap which is a square image. 但是我有一个像素图,它是一个正方形图像。 Is it possible to adapt the pixmap in such a way that it becomes rounded?
是否可以以使其变圆的方式来适应像素图?
I have found the setMask()
function on the QPixmap
, which I can maybe use. 我在
QPixmap
上找到了setMask()
函数,可以使用它。 But how would I make a bitmap that masks the edges of my QPixmap
? 但是,我将如何制作一个掩盖
QPixmap
边缘的位图?
Or is there a better way for this? 还是有更好的方法呢?
This is how you can prepare a QPixmap
with rounded corners: 这是准备带圆角的
QPixmap
:
const QPixmap orig = QPixmap("path to your image");
// getting size if the original picture is not square
int size = qMax(orig.width(), orig.height());
// creating a new transparent pixmap with equal sides
QPixmap rounded = QPixmap(size, size);
rounded.fill(Qt::transparent);
// creating circle clip area
QPainterPath path;
path.addEllipse(rounded.rect());
QPainter painter(&rounded);
painter.setClipPath(path);
// filling rounded area if needed
painter.fillRect(rounded.rect(), Qt::black);
// getting offsets if the original picture is not square
int x = qAbs(orig.width() - size) / 2;
int y = qAbs(orig.height() - size) / 2;
painter.drawPixmap(x, y, orig.width(), orig.height(), orig);
Then you can use the resulting pixmap to set a QPushButton
icon: 然后,您可以使用生成的像素图设置
QPushButton
图标:
QPushButton *button = new QPushButton(this);
button->setText("My button");
button->setIcon(QIcon(rounded));
And of course you have a second option to use some image editor to prepare images with rounded corners beforehand. 当然,您还有第二种选择,可以使用某些图像编辑器来预先准备带有圆角的图像。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.