我也會回答我自己的問題,但不會將其標記爲解決方案,因爲我請求了上面給出的簡單問題。畢竟,我最終使用的並不是一個簡單的解決方案,所以任何需要做類似工作並有時間去玩的人都可以在這裏找到我的最終工作代碼。這個想法是擴展QLabel並重載setPixmap和drawEvent方法。
QPictureLabel.hpp(頭文件)
#include "QImage.h"
#include "QPixmap.h"
#include "QLabel.h"
class QPictureLabel : public QLabel
{
private:
QPixmap _qpSource; //preserve the original, so multiple resize events won't break the quality
QPixmap _qpCurrent;
void _displayImage();
public:
QPictureLabel(QWidget *aParent) : QLabel(aParent) { }
void setPixmap(QPixmap aPicture);
void paintEvent(QPaintEvent *aEvent);
};
QPictureLabel.cpp(實現)
#include "QPainter.h"
#include "QPictureLabel.hpp"
void QPictureLabel::paintEvent(QPaintEvent *aEvent)
{
QLabel::paintEvent(aEvent);
_displayImage();
}
void QPictureLabel::setPixmap(QPixmap aPicture)
{
_qpSource = _qpCurrent = aPicture;
repaint();
}
void QPictureLabel::_displayImage()
{
if (_qpSource.isNull()) //no image was set, don't draw anything
return;
float cw = width(), ch = height();
float pw = _qpCurrent.width(), ph = _qpCurrent.height();
if (pw > cw && ph > ch && pw/cw > ph/ch || //both width and high are bigger, ratio at high is bigger or
pw > cw && ph <= ch || //only the width is bigger or
pw < cw && ph < ch && cw/pw < ch/ph //both width and height is smaller, ratio at width is smaller
)
_qpCurrent = _qpSource.scaledToWidth(cw, Qt::TransformationMode::FastTransformation);
else if (pw > cw && ph > ch && pw/cw <= ph/ch || //both width and high are bigger, ratio at width is bigger or
ph > ch && pw <= cw || //only the height is bigger or
pw < cw && ph < ch && cw/pw > ch/ph //both width and height is smaller, ratio at height is smaller
)
_qpCurrent = _qpSource.scaledToHeight(ch, Qt::TransformationMode::FastTransformation);
int x = (cw - _qpCurrent.width())/2, y = (ch - _qpCurrent.height())/2;
QPainter paint(this);
paint.drawPixmap(x, y, _qpCurrent);
}
用法:與使用普通標籤,用於顯示圖像wirthout setScaledContents
img_Result = new QPictureLabel(ui.parent);
layout = new QVBoxLayout(ui.parent);
layout->setContentsMargins(11, 11, 11, 11);
ui.parent->setLayout(layout);
layout->addWidget(img_Result);
//{...}
QPixmap qpImage(qsImagePath);
img_Result->setPixmap(qpImage);
對於一個快速的解決方案,這是一個保護程序,但它通過拉伸圖像(即給了我一個非常難看的結果:沒有保持寬高比)。無論如何,我會將其標記爲解決方案。謝謝。 – SinistraD 2011-04-22 22:44:29
使用PyQt5,此解決方案不起作用。 'setScaledContents'似乎對顯示的圖像大小沒有任何影響。 – ely 2017-05-15 20:40:02