1
votes

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?

1
There is any transparency on your icon? Did you try to use setStyleSheet(); ? It allows you to use CSS on your QPushButton :) - Antoine Morrier
The icon is a square of a dynamic color. The opacity is variable per button. Not sure how stylesheets would help here. I'm setting the icon by using QPushButton::setIcon(). Is it possible to manipulate this icon through stylesheets? - Frank
I don't really understand what the problem is... If your icon has transparent value, you could use them. However, if you just want to have a "rounded" icon, one way could be to use a QLabel (set with StyleSheet for example, border radius etc) and put this QLabel on top of your QPushButton? - Antoine Morrier

1 Answers

2
votes

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.