Search code examples
c++qt-creatorqfiledialog

In qt QFileDialog setsuffix is not working in linux, how to solve?


I am working on a Save dialog for my qt app. Everything works, but if no file extension is added behind the filename, it won't automatically be saved with the file extension although the filter is selected.

I know i need to set a defaultsuffix option, but even if i do, then it still won't add the extension automatically if its not given.

I found several other similar questions, where i read it works in windows but it could fail on linux distro's. If so, is there a simple workaround? Because right now, i don't have a working solution...

void MainWindow::on_actionSave_Chart_As_triggered()
{
    QFileDialog *fileDialog = new QFileDialog;
    fileDialog->setDefaultSuffix("files (*);;AstroQt aqt (*.aqt)");
    QString fileName = fileDialog->getSaveFileName(this, "Save Radix", ui->label_2->text() +".aqt", "AstroQT(*.aqt)");

    qDebug() << " save file name " << fileName << endl;

    QFile file(fileName);
    if (!file.open(QFile::WriteOnly | QFile::Text)) {
        QMessageBox::warning(this, "Warning", "Cannot save file: " + file.errorString());
        return;
    }

    setWindowTitle(fileName);

    QTextStream out(&file);
    QString text = "text that will be saved...";

    out << text;
    file.close();
}

Edit: After trying multiple solutions, none seemed to work. But it should have, i guess. Why else is there a aftersuffix function...? For now i solved it doing it manually. But i'm not happy with it, there should be a better solution/explanation.

// add extension if none is found.
if(!fileName.endsWith(".aqt"))
   fileName.append(".aqt");

Solution

  • If you use the static method getSaveFileName things seems to work correctly:

    #include <QFileDialog>
    #include <QApplication>
    #include <QDebug>
    
    int main(int argc, char *argv[]) {
        QApplication app(argc, argv);
        QString fileName = QFileDialog::getSaveFileName(
            nullptr, QObject::tr("Save File"),
            "teste.aqt",
            QObject::tr("AstroQt (*.aqt)"));
    
        qDebug() << " save file name " << fileName << endl;
        return app.exec();
    }
    

    I get the correct file name with the extension, if I type something without the extension.