QFileDialog that accepts a single file or a single directory

前端 未结 4 1360
有刺的猬
有刺的猬 2021-02-13 23:46

Is it possible to show a QFileDialog where the user can select a file or a directory, either one?

QFileDialog::getOpenFileName() accepts only files, while

4条回答
  •  无人共我
    2021-02-14 00:23

    Quite old question but I think I have a simpler solution than most for the lazy ones. You can connect the signal currentChanged of QFileDialog with a function that dynamically changes the fileMode.

    //header
    class my_main_win:public QMainWindow  
    {
    private:
        QFileDialog file_dialog;    
    }
    
    //constructor 
    
    my_main_win(QWidget * parent):QMainWindow(parent)
    {
        connect(&file_dialog,QFileDialog::currentChanged,this,[&](const QString & str)
            {
            QFileInfo info(str);
            if(info.isFile())
                file_dialog.setFileMode(QFileDialog::ExistingFile);
            else if(info.isDir())
                file_dialog.setFileMode(QFileDialog::Directory);
        });
    }
    

    And then simply call file_dialog as you would.

    if(file_dialog.exec()){
        QStringList dir_names=file_dialog.selectedFiles():
    }
    

提交回复
热议问题