New in Qt 5.15: Moving Files to the Trash in a Portable Way

New in Qt 5.15: Moving Files to the Trash in a Portable Way

By Jeff Tranter

The QFile class in Qt 5.15.0 provides an API that supports moving files to the trash in a portable way. It works on Windows, macOS, and on Linux desktop platforms that support the freedesktop.org specification.

Two new methods are provided: bool QFile::moveToTrash() moves the file associated with a QFile instance to the trash, returning true if it succeeds. In addition, it sets the object's fileName() to the path where the file can be found in the trash.

The static method bool QFile::moveToTrash(const QString &fileName, QString *pathInTrash = nullptr) performs a similar function, but accepts the file name as an argument and does not require a QFile instance. It sets the trash path to an optional second parameter passed to it.

Both APIs will return false on platforms that don't have move-to-trash support.

Example

I wrote a simple widget-based Qt application that demonstrates the new API. It allows selecting a file, moving it to the trash, and restoring it. Some screenshots are shown below. You can find the source code for it here.



Restoring a file in the example is done rather simplistically by renaming it from the trash location back to the original location. To fully comply with the freedesktop.org trash specification on Linux you could, for example, use a command line tool from the trash-cli package, but this would not be portable.

While this new API has very limited capabilities (it can't directly undelete files, for example), this is a handy new feature in Qt to keep in mind. It will make your desktop application a little more user friendly and integrated with the desktop platform while still being portable.

For more technical content on Qt, visit our main Qt/QML blog page.