Frank
Frank

Reputation: 2706

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. 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. But how would I make a bitmap that masks the edges of my QPixmap?

Or is there a better way for this?

Upvotes: 1

Views: 2008

Answers (1)

hank
hank

Reputation: 9853

This is how you can prepare a QPixmap with rounded corners:

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

Upvotes: 3

Related Questions