我試着用phyatt的AspectRatioPixmapLabel
類,但在經歷了幾個問題:
- 有時我的應用程序進入調整事件的無限循環。我追溯到
QLabel::setPixmap(...)
調用resizeEvent方法內,因爲QLabel
實際上調用updateGeometry
裏面setPixmap
,這可能會觸發調整大小事件...
heightForWidth
似乎是由含有小部件(在我的情況下,QScrollArea
)被忽略,直到我開始設置大小政策的標籤,顯式調用policy.setHeightForWidth(true)
- 我希望標籤永遠不會比原來的像素圖的大小
更多
QLabel
的實施minimumSizeHint()
做了一些魔法包含文本標籤,但總是重置大小策略,將默認的,所以我不得不將其覆蓋
這就是說,這裏是我的解決方案。我發現我可以使用setScaledContents(true)
並讓QLabel
處理調整大小。 當然,這取決於包含小部件/佈局以表彰heightForWidth
。
aspectratiopixmaplabel.h
#ifndef ASPECTRATIOPIXMAPLABEL_H
#define ASPECTRATIOPIXMAPLABEL_H
#include <QLabel>
#include <QPixmap>
class AspectRatioPixmapLabel : public QLabel
{
Q_OBJECT
public:
explicit AspectRatioPixmapLabel(const QPixmap &pixmap, QWidget *parent = 0);
virtual int heightForWidth(int width) const;
virtual bool hasHeightForWidth() { return true; }
virtual QSize sizeHint() const { return pixmap()->size(); }
virtual QSize minimumSizeHint() const { return QSize(0, 0); }
};
#endif // ASPECTRATIOPIXMAPLABEL_H
aspectratiopixmaplabel.cpp
#include "aspectratiopixmaplabel.h"
AspectRatioPixmapLabel::AspectRatioPixmapLabel(const QPixmap &pixmap, QWidget *parent) :
QLabel(parent)
{
QLabel::setPixmap(pixmap);
setScaledContents(true);
QSizePolicy policy(QSizePolicy::Maximum, QSizePolicy::Maximum);
policy.setHeightForWidth(true);
this->setSizePolicy(policy);
}
int AspectRatioPixmapLabel::heightForWidth(int width) const
{
if (width > pixmap()->width()) {
return pixmap()->height();
} else {
return ((qreal)pixmap()->height()*width)/pixmap()->width();
}
}
通過動態變化你是指像素數據還是維度? –
我指的是當前佈局中'QLabel'的尺寸。 QPixmap應該保持其大小,內容和維度。此外,調整大小(實際上縮小)會「自動地」發生,以填充可用空間 - 最初爲「QPixmap」的大小。所有這些都是通過子類化來完成的...... – marvin2k