Add a toggle to RDLabel to preserve the aspect ratio of its pixmap

This commit is contained in:
baldurk
2017-05-30 17:08:37 +01:00
parent c95f7c4cea
commit 26862d92b2
2 changed files with 34 additions and 0 deletions
+29
View File
@@ -60,3 +60,32 @@ void RDLabel::leaveEvent(QEvent *event)
QLabel::leaveEvent(event);
}
void RDLabel::resizeEvent(QResizeEvent *event)
{
const QPixmap *p = pixmap();
if(m_preserveRatio && p)
{
QRect r = rect();
float pratio = float(p->width()) / float(p->height());
float rratio = float(r.width()) / float(r.height());
if(pratio > rratio)
{
int correctHeight = int(r.width() / pratio);
int margin = (r.height() - correctHeight) / 2;
setContentsMargins(0, margin, 0, margin);
}
else
{
int correctWidth = int(r.height() * pratio);
int margin = (r.width() - correctWidth) / 2;
setContentsMargins(margin, 0, margin, 0);
}
}
}
+5
View File
@@ -33,6 +33,8 @@ public:
explicit RDLabel(QWidget *parent = 0);
~RDLabel();
void setPreserveAspectRatio(bool preserve) { m_preserveRatio = preserve; }
bool preserveAspectRatio() { return m_preserveRatio; }
signals:
void clicked(QMouseEvent *event);
void doubleClicked(QMouseEvent *event);
@@ -46,4 +48,7 @@ protected:
void mouseMoveEvent(QMouseEvent *event) override;
void mouseDoubleClickEvent(QMouseEvent *event) override;
void leaveEvent(QEvent *event) override;
void resizeEvent(QResizeEvent *event) override;
bool m_preserveRatio = false;
};