未在升级标签子类上绘制像素图

问题描述 投票:0回答:1

我对

QLabel
进行子类化并通过
QPixmap
绘制
QPainter
,它工作正常,问题是我无法更改像素图的图像路径并重新调用
paintEvent
函数,以便它重新绘制带有新图像的像素图。

我从 Qt Designer 添加了一个标签(即拖放),然后将其提升到这个子类。

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

我从

painEvent
收到此错误:

QPixmap::scaled:像素图是一个空像素图

qt subclass qt-designer qlabel paintevent
1个回答
0
投票
userAvatar *avatar = new userAvatar(nullptr);
avatar->setPath("E:/NetWork__Installs/kitty meme.jpg");

这不会添加到用户界面中,它不会可见,它的

paintEvent
不会被调用,这意味着您得到的错误不是来自该对象。

确实发出该错误的

userAvatar
ui_widget.h
中实例化并且可见。

要在用户界面中设置

photoLocation
userAvatar
,请使用以下命令:

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

yourUserAvatar
是您在 Qt Designer 中命名为
userAvatar
的任何内容。

© www.soinside.com 2019 - 2024. All rights reserved.