問題描述
我使用 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 的大小,同時保持其縱橫比的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!