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 的大小,同时保持其纵
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
