qt 获取用户缩放_Qt-如何创建随窗口缩放并保持纵横比的图像?

本文介绍如何在Qt中创建一个QLabel,该标签中的图像能根据窗口大小变化而缩放,同时保持图像的原始纵横比。通过使用QPixmap的scaled()方法,实现了在窗口调整大小时自动缩放图像并保持比例的功能。示例代码中展示了一个自定义的LabelImage类,它继承自QLabel,并覆盖了resizeEvent()方法以实现所需的缩放行为。
摘要由CSDN通过智能技术生成

bd96500e110b49cbb3cd949968f18be7.png

I'm trying to create image in QT (inside label) that would change size according to changes in window size, but also would keep aspect ratio.

What's the best way to do it?

解决方案

You tagged this question with linux. I develop on Windows 10 - the closest to Linux I have at hand is cygwin. Thus, I solved it in VS2013 but, hey, this is C++ with Qt. It should be portable...

Actually, QPixmap::scaled() has everything built-in what's necessary for scaling by keeping the aspect ratio. Thus, my solution is rather short plugging the QLabel and QPixmap together.

// standard C++ header:

#include

#include

// Qt header:

#include

#include

#include

#include

#include

#include

using namespace std;

class LabelImage: public QLabel {

private:

QPixmap _qPixmap, _qPixmapScaled;

public:

void setPixmap(const QPixmap &qPixmap) { setPixmap(qPixmap, size()); }

protected:

virtual void resizeEvent(QResizeEvent *pQEvent);

private:

void setPixmap(const QPixmap &qPixmap, const QSize &size);

};

void LabelImage::resizeEvent(QResizeEvent *pQEvent)

{

QLabel::resizeEvent(pQEvent);

setPixmap(_qPixmap, pQEvent->size());

}

void LabelImage::setPixmap(const QPixmap &qPixmap, const QSize &size)

{

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值