圈子用户头像问题

时间:2018-01-27 10:40:29

标签: c++ qt windows-applications

我想用图片圈制作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;");

0_1517048799005_2018-01-27_122604.png

它只围绕QLabel,而不是图像。怎么解决?感谢。

更新

唯一的方法是覆盖paintEvent

QLabel

代码:

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);
}

0_1517054607704_2018-01-27_140145.png

图像已圆整但未正确缩放。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

尝试在标签上设置掩码,如:

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

答案 1 :(得分:0)

通过覆盖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);
}

<强>结果:

enter image description here