我也会回答自己的问题,但不会将其标记为解决方案,因为我要求一个简单的解决方案,而上面已经给出了。最终我使用了一个并不太简单的解决方案,所以任何需要做类似事情并有时间尝试的人,这是我的最终工作代码。思路是扩展QLabel并重载setPixmap和drawEvent方法。
QPictureLabel.hpp(头文件)
#include "QImage.h"
#include "QPixmap.h"
#include "QLabel.h"
class QPictureLabel : public QLabel
{
private:
QPixmap _qpSource;
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())
return;
float cw = width(), ch = height();
float pw = _qpCurrent.width(), ph = _qpCurrent.height();
if (pw > cw && ph > ch && pw/cw > ph/ch ||
pw > cw && ph <= ch ||
pw < cw && ph < ch && cw/pw < ch/ph
)
_qpCurrent = _qpSource.scaledToWidth(cw, Qt::TransformationMode::FastTransformation);
else if (pw > cw && ph > ch && pw/cw <= ph/ch ||
ph > ch && pw <= cw ||
pw < cw && ph < ch && cw/pw > ch/ph
)
_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);
}
用法:与正常标签显示图像的方式相同,但不使用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);
QSizePolicy.Ignored
似乎对图像是否调整大小没有影响。 - ely