Finding locations with QDesktopServices

· by Benjamin Meyer · 1 min read · original post ↗

·

One small feature that I have wanted Qt to have when writing applications was a way to get some common directories. Where is the desktop, the music directory, or even the location where I should store my data files? On Mac, Windows and Linux these have always been different. A big problem in adding this feature has been Linux with the lack of any sort of standard, but this past year with the xdg-user-dirs spec released and with distributions like Ubuntu and others adopting it I decided it was a good time to revisit the problem. In Qt 4.4 QDesktopServices got a new function, storageLocation that returns the default system directory where files of a certain type belong. The currently supported types are: Desktop, Documents, Fonts, Applications, Music, Movies, Pictures, Temp, Home, and Data. Note that storage location can return an empty string or even a directory that currently doesn’t exists such as where the Music directory should be, but the user deleted it.

In a media player you could set the initial directory of the file dialog to open the music directory.


    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),  

                                                     QDesktopServices::storageLocation(QDesktopServices::MusicLocation),  

                                                     tr("Media Files (*.ogg *.mp3 *.flac *.wav)"));

Or when looking to store some application data, say palettes for an image editor.


    QString directory = QDesktopServices::storageLocation(QDesktopServices::DataLocation);  

    // embedded platforms currently don't define this location and you don't want to write to /foo  

    if (directory.isEmpty())  

        directory = QDir::homePath() + "/." + QCoreApplication::applicationName();  

    // the first time I am saving data  

    if (!QFile::exists(directory)) {  

        QDir dir;  

        dir.mkpath(directory);  

    }  

    // save my data  

    QFile file(directory + "/custompalettes.dat");  

    ...

QtKDE

More on KDE

More from Benjamin Meyer