This is an example of how I want the QPixmap
to be contained inside the QLabel
. The image keeps its aspect ratio and fills the given dimension. It will be clipped to fit.
Here is the CSS equivalent:
object-fit: cover;
This almost does what I want, but it stretches the image to cover the QLabel
, so the aspect ratio isn't reserved.
QPixmap *img = new QPixmap("image.png");
ui->label->setPixmap(*img);
ui->label->setScaledContents(true);
delete img;
Can be implemented as QWidget
subclass using QTransform
.
class Label : public QWidget
{
Q_OBJECT
public:
explicit Label(QWidget *parent = nullptr);
void setPixmap(const QPixmap& image);
protected:
void paintEvent(QPaintEvent *event);
QPixmap mPixmap;
};
Label::Label(QWidget *parent) : QWidget(parent) {
}
void Label::setPixmap(const QPixmap &pixmap)
{
mPixmap = pixmap;
update();
}
void Label::paintEvent(QPaintEvent *event)
{
if (mPixmap.isNull()) {
return;
}
double width = this->width();
double height = this->height();
double pixmapWidth = mPixmap.width();
double pixmapHeight = mPixmap.height();
double scale = qMax(width / pixmapWidth, height / pixmapHeight);
QTransform transform;
transform.translate(width / 2, height / 2);
transform.scale(scale, scale);
transform.translate(-pixmapWidth / 2, -pixmapHeight / 2);
QPainter painter(this);
painter.setTransform(transform);
painter.drawPixmap(QPoint(0,0), mPixmap);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.