You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Linux下Qt QFileDialog setDefaultSuffix失效问题及解决问询

Fix QFileDialog's Default Suffix Not Working on Linux

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 getSaveFileName method doesn't inherit any settings from manually created QFileDialog instances. Use one approach consistently.
  • Proper setDefaultSuffix usage: Pass just the suffix string (e.g., "aqt", not ".aqt" or "*.aqt"). Qt automatically handles adding the dot when needed.
  • Explicit filter selection: Use selectNameFilter to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:16:41