Tuesday, June 7, 2011

Check for valid file extension provided by QFileDialog

QFileDialog is used to select files from a specific directory. getOpenFileName() static function of QFileDialog returns the name of the selected file. Also, a filter can be set for the type of the file selected by the user by separating types with ';;'.
Ex:
"All Files (*.*);;JPEG (*.jpeg *.jpg);;PNG (*.png)"
In order to check for file extension of a file name provided by BrowseDialog which is extending QDialog and containing QFileDialog in its sl_browseImage() slot,
bool isValidImageFile(const QString& str)
function is implemented.
isValidImageFile function takes the full path of the file and splits it into pieces to find the file extension from the original QString instance.
File extension is placed after the last period character, so the last member of the QStringList contains the file extension that we are looking for.
By getting the upper case of the file extension which is provided by the client, we can search for a suitable match in our accepted file extension list. If the provided file extension is not in our list, then the derived custom QDialog opens a QMessageBox and gives a warning to the client.
Sample project started as a QT Gui Application and contains main.cpp, BrowseFileDialog.h and BrowseFileDialog.cpp files.

Project Directory Structure in Qt Creator IDE :

BrowseFileDialog.pro is the project configuration file contains:
TARGET = BrowseFileDialog
CONFIG   += core gui
TEMPLATE = app
SOURCES += main.cpp \
    BrowseFileDialog.cpp
HEADERS += \
    BrowseFileDialog.h

main.cpp file contains the custom QDialog instance and shows it.
#include <QApplication>
#include "BrowseFileDialog.h"
int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    BrowseFileDialog w;
    w.show();
    return a.exec();
}

BrowseFileDialog.h file is the derived QDialog class header file. Custom QDialog contains signals and slots to be associated with buttons on the dialog.
#ifndef BROWSEFILEDIALOG_H
#define BROWSEFILEDIALOG_H
#include <QDialog>
#include <QLineEdit>
#include <QPushButton>
#include <QLabel>

class BrowseFileDialog : public QDialog
{
    Q_OBJECT
public:
    BrowseFileDialog(QWidget *parent = 0);
    ~BrowseFileDialog();
public slots:
    void sl_browseImage();
private:
    void initLayout();
    void initConnections();
    bool isValidImageFile(const QString& str);
    QLabel* label;
    QLineEdit* lineEdit;
    QPushButton* pushButtonBrowse;
    QPushButton* pushButtonOK;
    QPushButton* pushButtonCancel;
};
#endif // BROWSEFILEDIALOG_H

BrowseFileDialog.cpp file contains implementation details for extended QDialog class.
#include "BrowseFileDialog.h"
#include <QHBoxLayout>
#include <QFileDialog>
#include <QString>
#include <QMessageBox>
#include <QSpacerItem>
BrowseFileDialog::BrowseFileDialog(QWidget *parent) : QDialog(parent)
{
    initLayout();
    initConnections();
}

BrowseFileDialog::~BrowseFileDialog()
{
    delete label;
    delete lineEdit;
    delete pushButtonBrowse;
    delete pushButtonOK;
    delete pushButtonCancel;
}

void BrowseFileDialog::initLayout()
{
    QGridLayout* mainLayout = new QGridLayout(this);
    QHBoxLayout* hBoxLayout = new QHBoxLayout();
    hBoxLayout->setSpacing(0);
    hBoxLayout->setMargin(0);
    label = new QLabel("Image File Path :");
    lineEdit = new QLineEdit(this);
    lineEdit->setReadOnly(true);
    pushButtonBrowse = new QPushButton("Browse...");
    hBoxLayout->addWidget(label);
    hBoxLayout->addWidget(lineEdit);
    hBoxLayout->addWidget(pushButtonBrowse);
    QHBoxLayout* actionWidgetsHBoxLayout = new QHBoxLayout();
    pushButtonCancel = new QPushButton("Cancel");
    pushButtonOK = new QPushButton("OK");
    actionWidgetsHBoxLayout->addStretch();
    actionWidgetsHBoxLayout->addWidget(pushButtonCancel);
    actionWidgetsHBoxLayout->addWidget(pushButtonOK);
    mainLayout->addLayout(hBoxLayout,0,0);
    mainLayout->addLayout(actionWidgetsHBoxLayout,1,0);
    setLayout(mainLayout);
}

void BrowseFileDialog::initConnections()
{
    connect(pushButtonBrowse, SIGNAL(clicked()), this, SLOT(sl_browseImage()));
    connect(pushButtonOK, SIGNAL(clicked()), this, SLOT(accept()));
    connect(pushButtonCancel, SIGNAL(clicked()), this, SLOT(reject()));
}

void BrowseFileDialog::sl_browseImage()
{
    QString inputImagePath=QFileDialog::getOpenFileName(this,tr("Select Image File"),QDir::currentPath(),
                                                        tr("All Files (*.*);;JPEG (*.jpeg *.jpg);;PNG (*.png)"));
    if(isValidImageFile(inputImagePath))
        lineEdit->setText(inputImagePath);
    else {
            QMessageBox::information(this, tr("Error!"),
                    tr("Please Provide a valid input image with JPG,JPEG or PNG extension!"));
    }
}

bool BrowseFileDialog::isValidImageFile(const QString& strImageFileName)
{
    QStringList acceptedImageFileTypeList;
    acceptedImageFileTypeList << "JPG"<< "JPEG" << "PNG";
    QStringList splittedStrList = strImageFileName.split(".");
    if( ((splittedStrList.size())-1) >= 0) {
        QString fileExtensionToCheck = splittedStrList[((splittedStrList.size())-1)];
        if( acceptedImageFileTypeList.contains(fileExtensionToCheck.toUpper()) )
            return true;
        else
            return false;
    }
    else
        return false;
}

BrowseFileDialog:

Application created by QT Creator and uses Qt4.7 .

No comments:

Post a Comment