PDA

View Full Version : QFileDialog for choosing filename to save data



araglin
1st April 2009, 08:47
Hello!
Would you please tell me how to append filter text to filename as extension?

Found this solution:
http://www.qtcentre.org/forum/f-qt-programming-2/t-qfiledialog-and-file-extension-10502.html/?highlight=QFileDialog

but maybe there is a lighter one for such simple (I hope) operation?



void snapShot::on_actionSave_as_activated()
{
if ( preview->palette().brush ( backgroundRole() ).texture().isNull() )
{
QMessageBox::critical ( this,tr ( "Error" ),tr ( "Nothing to save" ),QMessageBox::Ok,0 );
return;
}

QString fName;
QString frmts;
QFileDialog fd ( this );
fd.setAcceptMode ( QFileDialog::AcceptSave );
fd.setWindowTitle ( tr ( "Save as..." ) );

QStringList filters ( fd.nameFilters() );
filters << tr ( "PNG Images (*.png)" );
filters << tr ( "JPG Images (*.jpg *.jpeg)" );
filters << tr ( "XPM Images (*.xpm)" );
filters << tr ( "All Images (*.png *.jpg *.jpeg *.xpm)" );
fd.setNameFilters ( filters );

fd.setDirectory ( WorkDir );
fd.setFileMode ( QFileDialog::AnyFile );
if ( fd.exec() ==QDialog::Accepted )
{
QStringList files = fd.selectedFiles();
if ( !files.isEmpty() )
fName = files[0];
}
if ( fName.length() >0 )
{
if ( saveInFile ( fName ) ) {

if( !QFileInfo(fName).exists() )
fName.append(".png");
setWindowTitle( QFileInfo(fName).absoluteFilePath() + " - " + initWindowTitle);
}
}
}


When the user print "file.jpg" - it's ok, but when he print just "file" and then choose filter ("jpg") - exec() returns "file" without any information about desired extension...

Thanks in advance!

Hiker Hauk
1st April 2009, 09:03
Usually I use this,



QString fileName = QFileDialog::getOpenFileName(this, tr("Open Book"),
QDir::currentPath(),
tr("Books (*.book);;All Files (*)"));


See your online documentation for the method.

Filter - notice the name "filter" - only affects what you see on the file list.
It has nothing to do with what is returned. This is generic and not specific to Qt.

araglin
1st April 2009, 09:46
Thanks for your answer.
Actually I agree with you - filter must only filter, nothing more...
but there was a demand from users, so I solved this issue with the following code, maybe it will be helpful for someone else:


class MyFileDialog : public QFileDialog {
Q_OBJECT
public:
MyFileDialog (QWidget *parent = 0);
virtual ~MyFileDialog();
private slots:
void appendExtension( const QString& filter);
};

MyFileDialog::MyFileDialog(QWidget *parent): QFileDialog(parent) {
connect(this, SIGNAL(filterSelected( const QString& )), this, SLOT(appendExtension( const QString& )));
}
MyFileDialog::~MyFileDialog()
{
}
void MyFileDialog::appendExtension( const QString& filter)
{
setDefaultSuffix("png");
if (filter.contains("xpm") && !filter.contains("png") ) setDefaultSuffix("xpm");
else if (filter.contains("jpg") && !filter.contains("png") ) setDefaultSuffix("jpg");
qDebug() << defaultSuffix();
}