Qt5 Tutorial QMimeType and QMimeDatabase - 2020
In this tutorial, we will learn about QMimeType and QMimeDatabase.
Multipurpose Internet Mail Extensions (MIME) is an Internet standard that extends the format of email. MIME's use, however, has grown beyond describing the content of email and now is often used to describe content type in general including for the web (see Internet media type) and as a storage for rich content in some commercial products.
In this tutorial, we only deal with a file and learn how to get the right Mime type from the file.
Let's run the following code:
#include <QCoreApplication> #include <QString> #include <QStringList> #include <QFile> #include <QFileInfo> #include <QMimeDatabase> #include <QMimeType> #include <QDebug> // Returning a mimetype for a given QFile QString mimeReturn(const QFile& file) { QMimeDatabase mimeDatabase; QMimeType mimeType; mimeType = mimeDatabase.mimeTypeForFile(QFileInfo(file)); // mp4 mpg4 if(mimeType.inherits("video/mp4")) return "video/mp4"; // mpeg mpg mpe else if(mimeType.inherits("video/mpeg")) return "video/mpeg"; // ogv else if(mimeType.inherits("video/ogg")) return "video/ogg"; // qt, mov else if(mimeType.inherits("video/quicktime")) return "video/quicktime"; // avi else if(mimeType.inherits("video/x-msvideo")) return "video/x-msvideo"; // flv else if (mimeType.inherits("video/x-flv")) return "video/x-flv"; // webm else if (mimeType.inherits("video/webm")) return "video/webm"; // text else if (mimeType.inherits("text/plain")) return "text"; else return ""; } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QStringList List; List << "1.txt" << "2.mp4" << "3.webm" << "4.mov" << "5.flv"; foreach(QString item, List) { qDebug() << item << " ==> " << mimeReturn(item); } return a.exec(); }
The output from the run is:
"1.txt" ==> "text" "2.mp4" ==> "video/mp4" "3.webm" ==> "video/webm" "4.mov" ==> "video/quicktime" "5.flv" ==> "video/x-flv"
The key line of code is in mimeReturn():
mimeType = mimeDatabase.mimeTypeForFile(QFileInfo(file));
We have two types of methods for QMimeDatabase::mimeTypeForFile(), in this example, we're using the 1st form:
- QMimeType mimeTypeForFile(const QFileInfo & fileInfo, MatchMode mode = MatchDefault) const
- QMimeType mimeTypeForFile(const QString & fileName, MatchMode mode = MatchDefault) const
The inherit() function:
bool QMimeType::inherits(const QString & mimeTypeName) const
returns true if this mimetype is mimeTypeName, or inherits mimeTypeName,
or mimeTypeName is an alias for this mimetype.
So, in summay, the basic usage to get MIME type should look like this:
QMimeDatabase db; QMimeType mime = db.mimeTypeForFile(fileName); if (mime.inherits("text/plain")) { // The file is plain text, we can display it in a QTextEdit }
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization