Rozkata Buchinski
Rozkata Buchinski

Reputation: 11

How to specify which types of files you can open

I am currently starting to develop a QT desktop application, to edit the scripting language "Lua". The implementation should be pretty basic, opening Lua extension files, saving and editing them. The problem that i have stumbled upon is that I want to be able to open/save/edit just Lua files. While reading a QT documentation i stumbled upon an explanation of how you can open files for a so called "notepad" editor. They have provided the following example code:

QString fileName = QFileDialog::getOpenFileName(this, "Open the file");
QFile file(fileName);
currentFile = fileName;
if (!file.open(QIODevice::ReadOnly | QFile::Text)) {
    QMessageBox::warning(this, "Warning", "Cannot open file: " + file.errorString());
    return;
}
setWindowTitle(fileName);
QTextStream in(&file);
QString text = in.readAll();
ui->textEdit->setText(text);
file.close();

So here they basically add a condition where the file was unable to open, (it was in this line of code if (!file.open(QIODevice::ReadOnly | QFile::Text))) but they don't specify what the condition should look like if I only want to be able to open certain types of files (in my case, lua files). The same goes for the "save" option that they have displayed.. So my question is, how should I extend this condition, to check if the files has the given extension type for Lua ? Thanks in advance.

Upvotes: 0

Views: 709

Answers (2)

Zlatomir
Zlatomir

Reputation: 7034

getOpenFileName can take more arguments (has default values for some of the arguments), see the documentation here.

So your code will be something like:

QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),
                                            "", //default path here
                                            tr("Lua files (*.lua)"));

Upvotes: 2

ben10
ben10

Reputation: 241

You could try this: void QFileDialog::setNameFilter(const QString &filter)

Sets the filter used in the file dialog to the given filter.

/* If filter contains a pair of parentheses containing one or 
more filename-wildcard patterns, separated by spaces, then 
only the text contained in the parentheses is used as the filter. 
This means that these calls are all equivalent: */

dialog.setNameFilter("All Lua files (*.lua)");

Taken from the docs: https://doc.qt.io/qt-5/qfiledialog.html#setNameFilter

Upvotes: 0

Related Questions