imagescaling.cpp Example File
imagescaling/imagescaling.cpp
#include "imagescaling.h"
#include <qmath.h>
#include <functional>
Images::Images(QWidget *parent)
: QWidget(parent)
{
setWindowTitle(tr("Image loading and scaling example"));
resize(800, 600);
imageScaling = new QFutureWatcher<QImage>(this);
connect(imageScaling, &QFutureWatcher<QImage>::resultReadyAt, this, &Images::showImage);
connect(imageScaling, &QFutureWatcher<QImage>::finished, this, &Images::finished);
openButton = new QPushButton(tr("Open Images"));
connect(openButton, &QPushButton::clicked, this, &Images::open);
cancelButton = new QPushButton(tr("Cancel"));
cancelButton->setEnabled(false);
connect(cancelButton, &QPushButton::clicked, imageScaling, &QFutureWatcher<QImage>::cancel);
pauseButton = new QPushButton(tr("Pause/Resume"));
pauseButton->setEnabled(false);
connect(pauseButton, &QPushButton::clicked, imageScaling, &QFutureWatcher<QImage>::togglePaused);
QHBoxLayout *buttonLayout = new QHBoxLayout();
buttonLayout->addWidget(openButton);
buttonLayout->addWidget(cancelButton);
buttonLayout->addWidget(pauseButton);
buttonLayout->addStretch();
imagesLayout = new QGridLayout();
mainLayout = new QVBoxLayout();
mainLayout->addLayout(buttonLayout);
mainLayout->addLayout(imagesLayout);
mainLayout->addStretch();
setLayout(mainLayout);
}
Images::~Images()
{
imageScaling->cancel();
imageScaling->waitForFinished();
}
void Images::open()
{
if (imageScaling->isRunning()) {
imageScaling->cancel();
imageScaling->waitForFinished();
}
QStringList files = QFileDialog::getOpenFileNames(this, tr("Select Images"),
QStandardPaths::writableLocation(QStandardPaths::PicturesLocation),
"*.jpg *.png");
if (files.isEmpty())
return;
const int imageSize = 100;
qDeleteAll(labels);
labels.clear();
int dim = qSqrt(qreal(files.count())) + 1;
for (int i = 0; i < dim; ++i) {
for (int j = 0; j < dim; ++j) {
QLabel *imageLabel = new QLabel;
imageLabel->setFixedSize(imageSize,imageSize);
imagesLayout->addWidget(imageLabel,i,j);
labels.append(imageLabel);
}
}
std::function<QImage(const QString&)> scale = [imageSize](const QString &imageFileName) {
QImage image(imageFileName);
return image.scaled(QSize(imageSize, imageSize), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
};
imageScaling->setFuture(QtConcurrent::mapped(files, scale));
openButton->setEnabled(false);
cancelButton->setEnabled(true);
pauseButton->setEnabled(true);
}
void Images::showImage(int num)
{
labels[num]->setPixmap(QPixmap::fromImage(imageScaling->resultAt(num)));
}
void Images::finished()
{
openButton->setEnabled(true);
cancelButton->setEnabled(false);
pauseButton->setEnabled(false);
}