Linux下Qt QFileDialog setDefaultSuffix失效问题及解决问询
Let's start with the root cause of your problem: you're creating a QFileDialog instance and setting setDefaultSuffix on it, but then you call the static getSaveFileName method—which creates an entirely separate dialog instance. Your initial configuration is completely ignored! Windows might seem to work because the native file dialog there often auto-completes suffixes based on the filter, but Linux relies on Qt's explicit settings, hence the failure.
Here's the improved solution that works consistently across both Linux and Windows, eliminating the need for manual suffix checks:
Corrected Code
void MainWindow::on_actionSave_Chart_As_triggered() { // Create a non-static QFileDialog instance tied to your window QFileDialog fileDialog(this, "Save Radix", ui->label_2->text() + ".aqt"); // Configure it as a save dialog fileDialog.setAcceptMode(QFileDialog::AcceptSave); // Set your file filters (order matters; first is default if not selected) fileDialog.setNameFilters({"AstroQT (*.aqt)", "All files (*)"}); // Set the default suffix—note: only pass the suffix itself, no dot or wildcards fileDialog.setDefaultSuffix("aqt"); // Ensure the AstroQT filter is selected by default fileDialog.selectNameFilter("AstroQT (*.aqt)"); // Show the dialog and check if user clicked "Save" if (fileDialog.exec() == QDialog::Accepted) { QString fileName = fileDialog.selectedFiles().first(); 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(); } }
Key Notes:
- Avoid mixing static and non-static dialogs: The static
getSaveFileNamemethod doesn't inherit any settings from manually createdQFileDialoginstances. Use one approach consistently. - Proper
setDefaultSuffixusage: Pass just the suffix string (e.g.,"aqt", not".aqt"or"*.aqt"). Qt automatically handles adding the dot when needed. - Explicit filter selection: Use
selectNameFilterto ensure your preferred filter is active by default, so the suffix is applied correctly if the user doesn't change filters.
This approach ensures that the default suffix is automatically added whenever the user doesn't specify one, regardless of the OS. No more manual string checks needed!
内容的提问来源于stack exchange,提问作者Esocoder

