Search code examples
qtsubclassqt-designerqlabelpaintevent

Pixmap not drawn on promoted label subclass


I'm subClassing QLabel and painting a QPixmap via QPainter, it works fine, the problem is I can't change the image path of the pixmap and re-call the paintEvent function so it repaints the pixmap with the new Image.

I added a label from Qt Designer (i.e drag and drop) then promoted it to this subclass.

useravatar.h:

#ifndef USERAVATAR_H
#define USERAVATAR_H

#include <QLabel>
#include <QObject>
#include <QPen>
#include <QBrush>
#include <QPainter>
#include <QPaintEvent>

class userAvatar : public QLabel
{
    Q_OBJECT
public:
    QString photoLocation;
    userAvatar(QWidget *parent);
    void setPath(const QString &path);
private:
    void paintEvent(QPaintEvent *event) override;
};

#endif // USERAVATAR_H

useravatar.cpp:

#include "useravatar.h"
#include <unistd.h>

userAvatar::userAvatar(QWidget *parent) : QLabel(parent)
{
}

void userAvatar::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter painter(this);

    QPixmap pixmap(photoLocation);
    qDebug() << photoLocation; // outputs EMPTY string
    QPixmap scaled = pixmap.scaled(width(), height(), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation);

    QBrush bruch(scaled);
    bruch.setColor(Qt::black);
    painter.setBrush(bruch);

    painter.drawRoundedRect(0, 0, width(), height(), 100, 100);
}

void userAvatar::setPath(const QString &path)
{
    photoLocation = path;
    update();
}

widget.cpp:

#include "widget.h"
#include "ui_widget.h"
#include <QLabel>
#include "useravatar.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    
    userAvatar *avatar = new userAvatar(nullptr);
    avatar->setPath("E:/NetWork__Installs/kitty meme.jpg");
}

Widget::~Widget()
{
    delete ui;
}

I get this error from painEvent:

QPixmap::scaled: Pixmap is a null pixmap


Solution

  • userAvatar *avatar = new userAvatar(nullptr);
    avatar->setPath("E:/NetWork__Installs/kitty meme.jpg");
    

    This does not get added to the ui, it won't be visible, its paintEvent won't be called, meaning the error you get is not from this object.

    The userAvatar that does emit that error is instantiated in ui_widget.h and visible.

    To set photoLocation of the userAvatar in your ui, use this:

    ui->yourUserAvatar->setPath("/path/to/image.png");
    

    yourUserAvatar is whatever you named your userAvatar in Qt Designer.