How to maintain aspect ratio for QPixmap as a QWidget instead of QLabel

There are so many times that I have wanted an easy way to show a QPixmap on a form while maintaining the aspect-ratio of the image that I finally sat down and made one.  The single header file can be downloaded here: SpworksWidgetImage.zip. Extract the .h file and add it to any Qt project. It provides all of the necessary features to show an image when and where you want it using the SpworksWidgetImage class.

Usage:

//
// Don't forget to #include "spworkswidgetimage.h"
//

///////////
// SETUP //
///////////

SpworksWidgetImage* scaledImage = new SpworksWidgetImage();
scaledImage->SpworksWidgetImage_SetImagePath(":/anyImageResource.png");
this->layout()->addWidget(scaledImage);

///////////////////////
// OPTIONAL SETTINGS //
///////////////////////

// fill the widget to 75% of the widget's size
scaledImage->SpworksWidgetImage_SetScale(0.75);

// place the image in the bottom right corner of the widget
scaledImage->SpworksWidgetImage_SetAlignment(Qt::AlignRight | Qt::AlignBottom);

// paint the background of the entire widget white before painting the pixmap
scaledImage->SpworksWidgetImage_SetBackgroundColor(Qt::white);

// place a hidden border around the widget to keep the image off the edge
scaledImage->SpworksWidgetImage_SetBorderColor(QColor());
scaledImage->SpworksWidgetImage_SetBorderWidth(10);

//

Author: sirspot

I write software, love my wife and kids, do various house projects, play video games when I have time, and could use a little more sleep