Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio(Qt:调整包含 QPixmap 的 QLabel 的大小,同时保持其纵横比)
问题描述
我使用 QLabel 向用户显示更大的、动态变化的 QPixmap 的内容.根据可用空间使这个标签更小/更大会很好.屏幕尺寸并不总是像 QPixmap 一样大.
I use a QLabel to display the content of a bigger, dynamically changing QPixmap to the user. It would be nice to make this label smaller/larger depending on the space available. The screen size is not always as big as the QPixmap.
如何修改 QLabel 的 QSizePolicy 和 sizeHint() 来调整 QPixmap 的大小,同时保持原始 QPixmap 的纵横比?
How can I modify the QSizePolicy and sizeHint() of the QLabel to resize the QPixmap while keeping the aspect ratio of the original QPixmap?
我无法修改 QLabel 的 sizeHint(),将 minimumSize() 设置为零也无济于事.在 QLabel 上设置 hasScaledContents() 允许增长,但会破坏纵横比...
I can't modify sizeHint() of the QLabel, setting the minimumSize() to zero does not help. Setting hasScaledContents() on the QLabel allows growing, but breaks the aspect ratio thingy...
子类化 QLabel 确实有帮助,但是这个解决方案为一个简单的问题添加了太多代码......
Subclassing QLabel did help, but this solution adds too much code for just a simple problem...
是否有任何聪明的提示如何在没有子类化的情况下实现这个?
Any smart hints how to accomplish this without subclassing?
推荐答案
为了更改标签大小,您可以为标签选择合适的大小策略,例如扩展或最小扩展.
In order to change the label size you can select an appropriate size policy for the label like expanding or minimum expanding.
您可以通过在每次更改时保持纵横比来缩放像素图:
You can scale the pixmap by keeping its aspect ratio every time it changes:
QPixmap p; // load pixmap
// get label dimensions
int w = label->width();
int h = label->height();
// set a scaled pixmap to a w x h window keeping its aspect ratio
label->setPixmap(p.scaled(w,h,Qt::KeepAspectRatio));
您应该在两个地方添加此代码:
There are two places where you should add this code:
- 更新像素图时
- 在包含标签的小部件的
resizeEvent中
这篇关于Qt:调整包含 QPixmap 的 QLabel 的大小,同时保持其纵横比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Qt:调整包含 QPixmap 的 QLabel 的大小,同时保持其纵
基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
