圈子用户头像问题

Circle user avatar issue

我想用图圈QLabel

代码:

QLabel *label = new QLabel(this);
QPixmap avatarPixmap(":/Icon/default_avatar.png");
label->setPixmap(avatarPixmap);
label->setStyleSheet("border: 0.5px solid red; border-radius: 50%; background-clip: padding;");

它只舍入 QLabel,而不是图像。如何解决?谢谢。

更新:

唯一的方法是为 QLabel

覆盖 paintEvent

代码:

void AccountImage::paintEvent(QPaintEvent *event)
{
    QPixmap pixmap(":/Icon/default_avatar.png");
    QBrush brush(pixmap);
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setBrush(brush);
    painter.drawRoundedRect(0, 0, width(), height(), 100, 100);
    QLabel::paintEvent(event);
}

图像变圆了,但未正确缩放。有什么想法吗?

尝试在标签上设置遮罩,如:

int w = // set the width here
int h = // set the height here
QRect *rct = new QRect(0, 0, w, h);
QRegion *reg = new QRegion(*rct, QRegion::Ellipse);
label->setMask(*reg);

参见:http://doc.qt.io/archives/qt-4.8/qwidget.html#setMask

重写 QLabel paintEvent 方法的解决方案。

代码:

void AccountImage::paintEvent(QPaintEvent *event)
{
    QPixmap pixmap(":/Icon/my_avatar.png");
    QPixmap scaled = pixmap.scaled(width(), height(), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation);
    QBrush brush(scaled);
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setBrush(brush);
    painter.drawRoundedRect(0, 0, width(), height(), 100, 100);
    QLabel::paintEvent(event);
}

结果: