問(wèn)題描述
我使用 QLabel 向用戶顯示更大的、動(dòng)態(tài)變化的 QPixmap 的內(nèi)容.根據(jù)可用空間使這個(gè)標(biāo)簽更小/更大會(huì)很好.屏幕尺寸并不總是像 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()
來(lái)調(diào)整 QPixmap 的大小,同時(shí)保持原始 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?
我無(wú)法修改 QLabel 的 sizeHint()
,將 minimumSize()
設(shè)置為零也無(wú)濟(jì)于事.在 QLabel 上設(shè)置 hasScaledContents()
允許增長(zhǎng),但會(huì)破壞縱橫比...
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...
子類(lèi)化 QLabel 確實(shí)有幫助,但是這個(gè)解決方案為一個(gè)簡(jiǎn)單的問(wèn)題添加了太多代碼......
Subclassing QLabel did help, but this solution adds too much code for just a simple problem...
是否有任何聰明的提示如何在沒(méi)有子類(lèi)化的情況下實(shí)現(xiàn)這個(gè)?
Any smart hints how to accomplish this without subclassing?
推薦答案
為了更改標(biāo)簽大小,您可以為標(biāo)簽選擇合適的大小策略,例如擴(kuò)展或最小擴(kuò)展.
In order to change the label size you can select an appropriate size policy for the label like expanding or minimum expanding.
您可以通過(guò)在每次更改時(shí)保持縱橫比來(lái)縮放像素圖:
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));
您應(yīng)該在兩個(gè)地方添加此代碼:
There are two places where you should add this code:
- 更新像素圖時(shí)
- 在包含標(biāo)簽的小部件的
resizeEvent
中
這篇關(guān)于Qt:調(diào)整包含 QPixmap 的 QLabel 的大小,同時(shí)保持其縱橫比的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!