Archived:Save and Open Files with QFileDialogBox
Archived: This article is archived because it is not considered relevant for third-party developers creating commercial solutions today. If you think this article is still relevant, let us know by adding the template {{ReviewForRemovalFromArchive|user=~~~~|write your reason here}}.
Qt Quick should be used for all UI development on mobile devices. The approach described in this article (based on QWidget) is deprecated.
Qt Quick should be used for all UI development on mobile devices. The approach described in this article (based on QWidget) is deprecated.
This code example shows a simple QWidget application that performs file save and open operations using standard dialog APIs.
Article Metadata
Tested with
Devices(s): S60 Emulator
Compatibility
Platform(s): S60 5th Edition
Article
Keywords: QFileDialog,QFile
Created: mind_freak
(14 Jul 2009)
Last edited: hamishwillee
(11 Oct 2012)
Contents |
Overview
This example show how to use the following classes
- QFile - Performs the actual file operations
- QFileDialog - Responsible for the FileDialog GUI.
Mode selection
- This property holds the accept mode of the dialog.The action mode defines whether the dialog is for opening or saving files.
QFileDialog *filedialog=new QFileDialog(); dialog->setAcceptMode(QFileDialog::AcceptSave);//To save files,default is open mode.
Source Code
Code to create open dialog Box to load file
void Widget::loadme()//load a specific file
{
QString filename = QFileDialog::getOpenFileName(this);//getting the file name
QFile file(filename);
if (file.open(QIODevice::ReadOnly|QIODevice::Text)) //{if file is already open do nothing
ui->textEdit->setPlainText(QString::fromUtf8(file.readAll()));
FilePath = filename;
}
Code for "Save" and "saveAs" to save file
void Widget::saveme()
{
if(FilePath.isEmpty())
saveFileAs();
else
saveFile(FilePath);
}
void Widget::saveFile(const QString &name) //save the existing file
{
QFile file(name);
if (file.open(QIODevice::WriteOnly|QIODevice::Text))
{
file.write(ui->textEdit->toPlainText().toUtf8());
}
}
void Widget::saveFileAs() //save as a new file
{
FilePath = QFileDialog::getSaveFileName(this);
if(FilePath.isEmpty())
return;
saveFile(mFilePath);
}


What is the variable FilePath? It is not declared anywhere but used in the code.
Assuming that it is declared in the header file, you might want to add a note about this.
--croozeus 07:16, 23 February 2010 (UTC)
13 Sep
2009
14 Sep
2009