c++ - Qpushbutton 上的圆形图标

标签 c++ qt qpixmap 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));

当然,您还有第二种选择,即使用一些图像编辑器预先准备带有圆角的图像。

关于c++ - Qpushbutton 上的圆形图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36597124/

相关文章:

image - 缩小时 GraphicsView fitInView() 非常像素化的结果

qt - 如何将 QPixmap 对象保存到文件?

C++ : Binary Search Tree getHeight() access violation

c++ - 初始化中的指针转换

qt - QGraphicsItem中的ItemCoordinateCache和DeviceCoordinateCache有什么区别?

c++ - 如何更改 .pro 文件中 Qt Creator 的 OUT_PWD 设置

qt - 如何使qt qgraphicsview缩放不影响点画图案?

c++ - 使用整型变量检查用户输入是整数还是字符串

c++ - 通过交换到末尾从 vector 中删除

c++ - 如何在 OpenCV 中使用高斯过滤单列垫