PDA

View Full Version : Multiple Files



bilal
8th January 2018, 18:37
How we can open multiple files(images) in Qt. I have written a code but this only opens a single image. Here is the Qt code.


QFileDialog dialog(this);
dialog.setNameFilter(tr("Images (*.png *.xpm *.jpg)"));
dialog.setViewMode(QFileDialog::Detail);
dialog.setFileMode(QFileDialog::ExistingFiles);
QString fileName = QFileDialog::getOpenFileName(this,
tr("Open Images"), "C:/Users/hamza/Desktop/New folder", tr("Image Files (*.png *.jpg *.bmp);;All Files (*.*)"));
if (dialog.exec())
fileName=dialog.selectedFiles();
if (!fileName.isEmpty())
{
QImage image(fileName);
image = image.scaledToWidth(ui->label_pic->width(),Qt::SmoothTransformation);
ui->label_pic->setPixmap(QPixmap::fromImage(image));
}

d_stranz
9th January 2018, 03:19
Why are you using the static method QFileDialog::getOpenFileName() at the same time you are constructing a QFileDialog instance and using the non-static QFileDialog::exec() method? You either do it one way or the other, not both at the same time.



QList< QImage > images;

QFileDialog dialog(this);
dialog.setNameFilter(tr("Images (*.png *.xpm *.jpg)"));
dialog.setViewMode(QFileDialog::Detail);
dialog.setFileMode(QFileDialog::ExistingFiles);

if ( QDialog::Accepted == dialog.exec() )
{
QStringList filenames = dialog.selectedFiles();
QStringList::const_iterator it = filenames.begin();
QStringList::const_iterator eIt = filenames.end();
while ( it != eIt )
{
QString fileName = *it++;
if ( !fileName.isEmpty() )
{
QImage image;
if ( image.load( fileName ) )
images.push_back( image );
}
}
}


At the end of this piece of code, the QList< QImage > contains all of the images that could be opened successfully. It's up to you to write the UI that will display each of them. The code you posted above will only display a single image on a single QLabel. You'll have to fix that code.

You could look at the Flow Layout example (https://doc.qt.io/archives/qt-4.8/qt-layouts-flowlayout-example.html) for ideas. Take the Window.cpp file from that example, and instead of adding QPushButton instances to the flow layout, you could re-write the constructor to take your list of images:



#include "flowlayout.h"
#include "window.h"

Window::Window( const QList< QImage > & images )
{
FlowLayout *flowLayout = new FlowLayout;

QList< QImage >::const_iterator it = images.begin();
QList< QImage >::const_iterator eIt = images.end();
while ( it != eIt )
{
const QImage & image = *it++;
QLabel * pLabel = new QLabel( this );
pLabel->setPixmap( QPixmap::fromImage( image ) );
flowLayout->addWidget( pLabel );
}

setLayout(flowLayout);
setWindowTitle(tr("Images in a Flow Layout"));
}