| 1 | #include "CircularPixmap.h" |
| 2 | |
| 3 | #include <QPainter> |
| 4 | #include <QPainterPath> |
| 5 | |
| 6 | CircularPixmap::CircularPixmap(const QSize &size, QWidget *parent) |
| 7 | : QLabel(parent) |
| 8 | , mSize(size) |
| 9 | { |
| 10 | } |
| 11 | |
| 12 | CircularPixmap::CircularPixmap(const QString &filePath, QWidget *parent) |
| 13 | : QLabel(parent) |
| 14 | , mSize(50, 50) |
| 15 | { |
| 16 | QPixmap px(filePath); |
| 17 | px = px.scaled(mSize.width(), mSize.height()); |
| 18 | |
| 19 | setPixmap(filePath); |
| 20 | setFixedSize(mSize); |
| 21 | } |
| 22 | #include <QPaintEvent> |
| 23 | void CircularPixmap::paintEvent(QPaintEvent *e) |
| 24 | { |
| 25 | #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) |
| 26 | if (pixmap()) |
| 27 | #endif |
| 28 | { |
| 29 | const auto rect = e->rect(); |
| 30 | const auto startX = (rect.width() - mSize.width()) / 2; |
| 31 | const auto startY = mCenterPosition ? (rect.height() - mSize.height()) / 2 : 0; |
| 32 | |
| 33 | QPainter painter(this); |
| 34 | painter.setRenderHint(QPainter::Antialiasing); |
| 35 | |
| 36 | QPainterPath path; |
| 37 | path.addEllipse(startX, startY, mSize.width(), mSize.height()); |
| 38 | painter.setClipPath(path); |
| 39 | #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) |
| 40 | painter.drawPixmap(startX, 0, mSize.width(), mSize.height(), *pixmap()); |
| 41 | #else |
| 42 | painter.drawPixmap(startX, startY, mSize.width(), mSize.height(), pixmap(Qt::ReturnByValue)); |
| 43 | #endif |
| 44 | } |
| 45 | } |
| 46 | |