Qpushbutton 上的圆形图标
Rounded icon on Qpushbutton
我有一个 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));
当然,您还有第二种选择,即使用一些图像编辑器预先准备带有圆角的图像。
我有一个 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));
当然,您还有第二种选择,即使用一些图像编辑器预先准备带有圆角的图像。