Q按钮上的圆形图标

Rounded icon on Qpushbutton

本文关键字:图标 按钮      更新时间:2023-10-16

我有一个QPushButton,我想在其中添加一个带圆角的图标(通过使用QPushButton::setIcon()添加到按钮)。然而,我有一个像素图,它是一个正方形的图像。有可能调整像素图使其变圆吗?

我在QPixmap上找到了setMask()函数,也许我可以使用它。但是,我该如何制作一个位图来屏蔽QPixmap的边缘呢?

或者有更好的方法吗?

这就是如何准备圆角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);

然后,您可以使用生成的像素图设置QPushButton图标:

QPushButton *button = new QPushButton(this);
button->setText("My button");
button->setIcon(QIcon(rounded));

当然,你还有第二种选择,可以使用一些图像编辑器预先准备圆角图像。