当前位置: 首页>>代码示例>>C++>>正文


C++ QMimeDatabase::mimeTypeForFile方法代码示例

本文整理汇总了C++中QMimeDatabase::mimeTypeForFile方法的典型用法代码示例。如果您正苦于以下问题:C++ QMimeDatabase::mimeTypeForFile方法的具体用法?C++ QMimeDatabase::mimeTypeForFile怎么用?C++ QMimeDatabase::mimeTypeForFile使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在QMimeDatabase的用法示例。


在下文中一共展示了QMimeDatabase::mimeTypeForFile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: loadMedia

void MainWindow::loadMedia(){
  // mime database to detect file type
  QMimeDatabase db;

  // the mime type (to test if it is an audio file
  QMimeType type;

  // file list to be inserted into playlist
  QStringList filelist;

  // audio file to be opened
  QFileDialog d;
  filelist = d.getOpenFileNames(this,tr("Open File"),
                                "/home",
                                tr("Audio (*.wav *.mp3 *.ogg *.flac)"));

  // retrieve mime type
  for(QList<QString>::const_iterator it=filelist.begin(); it!= filelist.end(); it++){
    type = db.mimeTypeForFile(*it);
    // test if the file is an audio file
    // if yes, send it to the playlist
    if(type.name().startsWith("audio")){
      playlist->addMedia(QUrl::fromLocalFile(*it));
    }
  }
}
开发者ID:cadubentzen,项目名称:blokbox_Cadu-Dina,代码行数:26,代码来源:mainwindow.cpp

示例2: fi

QuickLaunchAction::QuickLaunchAction(const QString & fileName, QWidget * parent)
    : QAction(parent),
      m_valid(true)
{
    m_type = ActionFile;
    setText(fileName);
    setData(fileName);
    
    m_settingsMap["file"] = fileName;

    QFileInfo fi(fileName);
    if (fi.isDir())
    {
        QFileIconProvider ip;
        setIcon(ip.icon(fi));
    }
    else
    {
        QMimeDatabase db;
        XdgMimeType mi(db.mimeTypeForFile(fi));
        setIcon(mi.icon());
    }
    
    connect(this, SIGNAL(triggered()), this, SLOT(execAction()));
}
开发者ID:dbluelle,项目名称:lxqt-panel,代码行数:25,代码来源:quicklaunchaction.cpp

示例3: uploadFile

QNetworkReply* Parse::uploadFile(QUrl url, QString name)
{
    QString filePath = url.toLocalFile();
    if (!isReady() || !QFile::exists(filePath)) return NULL;

    if (name.isEmpty()) name = url.fileName();
    setEndPoint( "files/"+name);

    QMimeDatabase db;
    QMimeType mime = db.mimeTypeForFile(filePath);

    QFile file(filePath);
    if (mime.inherits("text/plain")){
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
            return NULL;
    }
    else{
        if (!file.open(QIODevice::ReadOnly ))
            return NULL;
    }

    initHeaders();
    setHeader(QNetworkRequest::ContentTypeHeader, mime.name().toUtf8());

    m_conn = connect(this, &BaaS::replyFinished, [=]( QJsonDocument json){
        disconnect(m_conn);
        if ( getHttpCode() == 201 ){
            currentObject = json.object();
            emit fileUploaded( currentObject);
        }

    } );

    return request( BaaS::POST, file.readAll() );
}
开发者ID:pockemul,项目名称:PockEmul,代码行数:35,代码来源:parse.cpp

示例4: readDirectory

void FolderListModel::readDirectory()
{
    this->beginResetModel();

    QFileInfoList fileinfolist = this->_directory.entryInfoList(QDir::AllDirs | QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks, QDir::DirsFirst);

    if(!this->_mimefilter.isEmpty())
    {
        QMimeDatabase mimedb;
        QStringList mimefilter = this->_mimefilter.split("/");
        this->_files.clear();

        foreach(const QFileInfo& fi, fileinfolist)
        {
            if(fi.isDir())
            {
                this->_files.append(fi);
                continue;
            }

            QMimeType mime = mimedb.mimeTypeForFile(fi.filePath());
            QStringList mimestring = mime.name().split("/");

            if(mimefilter[0] != mimestring[0])
                continue;

            if((mimefilter.length() > 1) && mimefilter[1] != mimestring[1])
                continue;

            this->_files.append(fi);
        }
    }
开发者ID:tkeisala,项目名称:harbour-sailorgram,代码行数:32,代码来源:folderlistmodel.cpp

示例5: QObject

EditWithMenu::EditWithMenu(const QUrl& url, QWidget* parent)
    : QObject(parent)
    , m_menu(0)
    , m_url(url)
{
    QMimeDatabase db;
    QMimeType type = db.mimeTypeForFile(url.path(), QMimeDatabase::MatchExtension);
    if ( !type.isValid() )
    {
        qCDebug(log_cervisia) << "Couldn't find mime type!";
        return;
    }

    m_offers = KMimeTypeTrader::self()->query(type.name());

    if( !m_offers.isEmpty() )
    {
        m_menu = new QMenu(i18n("Edit With"));

        KService::List::ConstIterator it = m_offers.constBegin();
        for( int i = 0 ; it != m_offers.constEnd(); ++it, ++i )
        {
            QAction* pAction = m_menu->addAction(QIcon::fromTheme((*it)->icon()), (*it)->name());
            pAction->setData(i);
        }

        connect(m_menu, SIGNAL(triggered(QAction*)),
                this, SLOT(actionTriggered(QAction*)));
    }
开发者ID:KDE,项目名称:cervisia,代码行数:29,代码来源:editwithmenu.cpp

示例6: startSearch

void FilesystemContentLister::startSearch()
{
    QMimeDatabase mimeDb;
    bool useThis(false);

    qDebug() << "Searching in" << d->locations;
    Q_FOREACH(const QString& folder, d->locations)
    {
        QDirIterator it(folder, QDirIterator::Subdirectories);
        while (it.hasNext())
        {
            QString filePath = it.next();
            QFileInfo info(filePath);

            if(info.isDir())
            {
                qApp->processEvents();
                continue;
            }
            useThis = false;
            QString mimetype = mimeDb.mimeTypeForFile(filePath, QMimeDatabase::MatchExtension).name();
//             qDebug() << useThis << mimetype << filePath;
            Q_FOREACH(const QString& type, d->mimetypes)
            {
                if(type == mimetype) {
                    useThis = true;
                    break;
                }
            }

            if(useThis)
            {
                QVariantHash metadata;
                metadata["created"] = info.created();

                KFileMetaData::UserMetaData data(filePath);
                if (data.hasAttribute("peruse.currentPage")) {
                    int currentPage = data.attribute("peruse.currentPage").toInt();
                    metadata["currentPage"] = QVariant::fromValue<int>(currentPage);
                }
                if (data.hasAttribute("peruse.totalPages")) {
                    int totalPages = data.attribute("peruse.totalPages").toInt();
                    metadata["totalPages"] = QVariant::fromValue<int>(totalPages);
                }

                emit fileFound(filePath, metadata);
            }
            qApp->processEvents();
        }
    }
    // This ensures that, should we decide to search more stuff later, we can do so granularly
    d->locations.clear();

    // Not entirely happy about this, but it makes things not break...
    // Previously, the welcome page in Peruse would end up unpopulated because a signal
    // was unreceived from the main window upon search completion (and consequently
    // application readiness)
    QTimer::singleShot(0, this, SIGNAL(searchCompleted()));
}
开发者ID:KDE,项目名称:peruse,代码行数:59,代码来源:FilesystemContentLister.cpp

示例7: mimeType

QByteArray FileAttachmentItem::mimeType() const
{
    if (!m_cachedMime.isEmpty())
        return m_cachedMime;

    QMimeDatabase mimeDb;
    m_cachedMime = mimeDb.mimeTypeForFile(fileName).name().toUtf8();
    return m_cachedMime;
}
开发者ID:karanluthra,项目名称:trojita,代码行数:9,代码来源:ComposerAttachments.cpp

示例8: queryFileInfo

/** ***************************************************************************/
void Files::Extension::handleQuery(Core::Query * query) {


    if ( query->searchTerm().startsWith('/') || query->searchTerm().startsWith("~") ) {

        QFileInfo queryFileInfo(query->searchTerm());

        // Substitute tilde
        if ( query->searchTerm()[0] == '~' )
            queryFileInfo.setFile(QDir::homePath()+query->searchTerm().right(query->searchTerm().size()-1));

        // Get all matching files
        QFileInfo pathInfo(queryFileInfo.path());
        if ( pathInfo.exists() && pathInfo.isDir() ) {
            QMimeDatabase mimeDatabase;
            QDir dir(pathInfo.filePath());
            for (const QFileInfo& fileinfo : dir.entryInfoList(QDir::AllEntries|QDir::Hidden|QDir::NoDotAndDotDot,
                                                               QDir::DirsFirst|QDir::Name|QDir::IgnoreCase) ) {
                if ( fileinfo.fileName().startsWith(queryFileInfo.fileName()) ) {
                    QMimeType mimetype = mimeDatabase.mimeTypeForFile(fileinfo.filePath());
                    query->addMatch(std::make_shared<File>(fileinfo.filePath(), mimetype),
                                    static_cast<short>(SHRT_MAX * static_cast<float>(queryFileInfo.fileName().size()) / fileinfo.fileName().size()));
                }
            }
        }
    }
    else
    {
        if ( QString("albert scan files").startsWith(query->searchTerm()) ) {
            shared_ptr<StandardItem> standardItem = std::make_shared<StandardItem>("org.albert.extension.files.action.index");
            standardItem->setText("albert scan files");
            standardItem->setSubtext("Update the file index");
            standardItem->setIconPath(":app_icon");

            shared_ptr<StandardAction> standardAction = std::make_shared<StandardAction>();
            standardAction->setText("Update the file index");
            standardAction->setAction([this](){ this->updateIndex(); });

            standardItem->setActions({standardAction});

            query->addMatch(standardItem);
        }

        // Search for matches
        const vector<shared_ptr<Core::Indexable>> &indexables = d->offlineIndex.search(query->searchTerm().toLower());

        // Add results to query
        vector<pair<shared_ptr<Core::Item>,short>> results;
        for (const shared_ptr<Core::Indexable> &item : indexables)
            // TODO `Search` has to determine the relevance. Set to 0 for now
            results.emplace_back(std::static_pointer_cast<File>(item), -1);

        query->addMatches(results.begin(), results.end());
    }
}
开发者ID:BoltsJ,项目名称:albert,代码行数:56,代码来源:main.cpp

示例9: if

// create table of file lists qualified for search
QHash<SearchWorker::WorkSet, QStringList> SearchWorker::createFileTable(QDir dir, QDir::Filter hidden, QHash<SearchWorker::WorkSet, bool> enabler)
{
    QHash<SearchWorker::WorkSet, QStringList> wtab;
    QStringList filetypefilters;

    if (!enabler[SearchWorker::EnableMimeType]) {
        if (enabler[SearchWorker::EnableTxt]) {
            filetypefilters.clear();
            filetypefilters << "*.txt";
            wtab[SearchWorker::EnableTxt] = dir.entryList(filetypefilters, QDir::Files | hidden);
        }
        if (enabler[SearchWorker::EnableHtml]) {
            filetypefilters.clear();
            filetypefilters << "*.html" << "*.htm";
            wtab[SearchWorker::EnableHtml] = dir.entryList(filetypefilters, QDir::Files | hidden);
        }
        if (enabler[SearchWorker::EnableSrc]) {
            filetypefilters.clear();
            filetypefilters << "*.cpp" << "*.c" << "*.h" << "*.py" << "*.sh" << "*.qml" << "*.js";
            wtab[SearchWorker::EnableSrc] = dir.entryList(filetypefilters, QDir::Files | hidden);
        }
        if (enabler[SearchWorker::EnableApps]) {
            filetypefilters.clear();
            filetypefilters << "*.desktop";
            wtab[SearchWorker::EnableApps] = dir.entryList(filetypefilters, QDir::Files | hidden);
        }
        if (enabler[SearchWorker::EnableSqlite]) {
            filetypefilters.clear();
            filetypefilters << "*.sqlite" << "*.sqlite3" << "*.db";
            wtab[SearchWorker::EnableSqlite] = dir.entryList(filetypefilters, QDir::Files | hidden);
        }
    }

    if (enabler[SearchWorker::EnableMimeType]) {
        filetypefilters.clear();
        QStringList names = dir.entryList(filetypefilters, QDir::Files | hidden);
        QMimeDatabase db;
        for (int i = 0 ; i < names.count() ; ++i) {
            QString fullpath = dir.absoluteFilePath(names.at(i));
            QMimeType mime = db.mimeTypeForFile(fullpath);
            if ( mime.inherits("application/x-sqlite3") ) {
                if (enabler[SearchWorker::EnableSqlite]) wtab[SearchWorker::EnableSqlite].append(names.at(i)); }
            else if ( mime.inherits("application/x-desktop") ) {
                if (enabler[SearchWorker::EnableApps]) wtab[SearchWorker::EnableApps].append(names.at(i)); }
            else if ( mime.inherits("text/html") ) {
                if (enabler[SearchWorker::EnableHtml]) wtab[SearchWorker::EnableHtml].append(names.at(i)); }
            else if ( mime.inherits("text/x-csrc") || mime.inherits("application/x-shellscript")
                   || mime.inherits("text/x-python") || mime.inherits("text/x-qml") ) {
                if (enabler[SearchWorker::EnableSrc]) wtab[SearchWorker::EnableSrc].append(names.at(i)); }
            else if ( mime.inherits("text/plain") ) {
                if (enabler[SearchWorker::EnableTxt]) wtab[SearchWorker::EnableTxt].append(names.at(i)); }
        }
    }
    return wtab;
}
开发者ID:sargo-devel,项目名称:harbour-searchnemo,代码行数:56,代码来源:searchworker.cpp

示例10: mimetype

KIso::KIso(const QString& filename, const QString & _mimetype)
        : KArchive(0L)
{
    KISOFUNC;
    KISODEBUG("Starting KIso: " << filename << " - type: " << _mimetype);

    m_startsec = -1;
    m_filename = filename;
    d = new KIsoPrivate;
    QString mimetype(_mimetype);
    bool forced = true;
    if (mimetype.isEmpty()) {
        QMimeDatabase db;
        QMimeType mt = db.mimeTypeForFile(filename, QMimeDatabase::MatchContent);
        if (mt.isValid())
            mimetype = mt.name();

        //qDebug() << "KIso::KIso mimetype=" << mimetype << endl;

        // Don't move to prepareDevice - the other constructor theoretically allows ANY filter
        if (mimetype == "application/x-tgz" || mimetype == "application/x-targz" ||  // the latter is deprecated but might still be around
                mimetype == "application/x-webarchive")
            // that's a gzipped tar file, so ask for gzip filter
            mimetype = "application/x-gzip";
        else if (mimetype == "application/x-tbz")   // that's a bzipped2 tar file, so ask for bz2 filter
            mimetype = "application/x-bzip2";
        else {
            // Something else. Check if it's not really gzip though (e.g. for KOffice docs)
            QFile file(filename);
            if (file.open(QIODevice::ReadOnly)) {
                char firstByte;
                char secondByte;
                char thirdByte;
                file.getChar(&firstByte);
                file.getChar(&secondByte);
                file.getChar(&thirdByte);
                if (firstByte == 0037 && secondByte == (char)0213)
                    mimetype = "application/x-gzip";
                else if (firstByte == 'B' && secondByte == 'Z' && thirdByte == 'h')
                    mimetype = "application/x-bzip2";
                else if (firstByte == 'P' && secondByte == 'K' && thirdByte == 3) {
                    char fourthByte;
                    file.getChar(&fourthByte);
                    if (fourthByte == 4)
                        mimetype = "application/x-zip";
                }
            }
        }
        forced = false;
    }

    prepareDevice(filename, mimetype, forced);
}
开发者ID:KDE,项目名称:krusader,代码行数:53,代码来源:kiso.cpp

示例11: showMetaDataFor

void InfoPanel::showMetaDataFor(const QModelIndex &index)
{
    showMetaData();

    const Archive::Entry *entry = m_model->entryForIndex(index);

    QMimeDatabase db;
    QMimeType mimeType;

    if (entry->isDir()) {
        mimeType = db.mimeTypeForName(QStringLiteral("inode/directory"));
    } else {
        mimeType = db.mimeTypeForFile(entry->fullPath(), QMimeDatabase::MatchExtension);
    }

    m_typeValueLabel->setText(mimeType.comment());

    if (!entry->property("owner").toString().isEmpty()) {
        m_ownerLabel->show();
        m_ownerValueLabel->show();
        m_ownerValueLabel->setText(entry->property("owner").toString());
    } else {
        m_ownerLabel->hide();
        m_ownerValueLabel->hide();
    }

    if (!entry->property("group").toString().isEmpty()) {
        m_groupLabel->show();
        m_groupValueLabel->show();
        m_groupValueLabel->setText(entry->property("group").toString());
    } else {
        m_groupLabel->hide();
        m_groupValueLabel->hide();
    }

    if (!entry->property("link").toString().isEmpty()) {
        m_targetLabel->show();
        m_targetValueLabel->show();
        m_targetValueLabel->setText(entry->property("link").toString());
    } else {
        m_targetLabel->hide();
        m_targetValueLabel->hide();
    }

    if (entry->property("isPasswordProtected").toBool()) {
        m_passwordLabel->show();
        m_passwordValueLabel->show();
    } else {
        m_passwordLabel->hide();
        m_passwordValueLabel->hide();
    }
}
开发者ID:KDE,项目名称:ark,代码行数:52,代码来源:infopanel.cpp

示例12: QUrl

void FileInfo::Private::resolvePath()
{
    path = QUrl(source);
    if(path.isEmpty())
        path = QUrl::fromLocalFile(source);

    if(path.isRelative())
        path = QUrl::fromLocalFile(QDir::current().absoluteFilePath(source));

    fileInfo = QFileInfo(path.toLocalFile());
    QMimeDatabase db;
    mimeType = db.mimeTypeForFile(fileInfo);
}
开发者ID:SfietKonstantin,项目名称:sailfish-office,代码行数:13,代码来源:FileInfo.cpp

示例13: getEpisodes

QStringList EpisodeFinder::getEpisodes(const QString &seasonPath, int season, int episode) const
{
    QDir seasonDir(seasonPath);
    QMimeDatabase db;
    QStringList files;
    foreach (const QFileInfo &fileInfo, seasonDir.entryInfoList()) {
        if (!fileInfo.isFile())
            continue;
        QMimeType mimeType = db.mimeTypeForFile(fileInfo);

        // must have got a video mime type
        if (!mimeType.name().startsWith("video/"))
            continue;

        if (season == -1) {
            files << fileInfo.absoluteFilePath();
            continue;
        }

        QString fileName = fileInfo.fileName();
        int fileSeason, fileEpisode;

        // SXXEXX expression?
        QRegularExpression re("\\bS([0-9]+)E([0-9]+)", QRegularExpression::CaseInsensitiveOption);

        QRegularExpressionMatch match = re.match(fileName);
        if (match.hasMatch()) {
            fileSeason = match.captured(1).toInt();
            fileEpisode = match.captured(2).toInt();
            if (fileSeason == season && fileEpisode == episode)
                files << fileInfo.absoluteFilePath();
            continue;
        }

        // SxE expression?
        re.setPattern("\\b([0-9]+)x([0-9]+)");

        match = re.match(fileName);
        if (match.hasMatch()) {
            fileSeason = match.captured(1).toInt();
            fileEpisode = match.captured(2).toInt();
            if (fileSeason == season && fileEpisode == episode)
                files << fileInfo.absoluteFilePath();
            continue;
        }

    }
    return files;
}
开发者ID:Guid75,项目名称:betaseeker,代码行数:49,代码来源:episodefinder.cpp

示例14: mimeTypeForName

void tst_QMimeDatabase::mimeTypeForName()
{
    QMimeDatabase db;
    QMimeType s0 = db.mimeTypeForName(QString::fromLatin1("application/x-zerosize"));
    QVERIFY(s0.isValid());
    QCOMPARE(s0.name(), QString::fromLatin1("application/x-zerosize"));
    QCOMPARE(s0.comment(), QString::fromLatin1("empty document"));

    QMimeType s0Again = db.mimeTypeForName(QString::fromLatin1("application/x-zerosize"));
    QCOMPARE(s0Again.name(), s0.name());

    QMimeType s1 = db.mimeTypeForName(QString::fromLatin1("text/plain"));
    QVERIFY(s1.isValid());
    QCOMPARE(s1.name(), QString::fromLatin1("text/plain"));
    //qDebug("Comment is %s", qPrintable(s1.comment()));

    QMimeType krita = db.mimeTypeForName(QString::fromLatin1("application/x-krita"));
    QVERIFY(krita.isValid());

    // Test <comment> parsing with application/rdf+xml which has the english comment after the other ones
    QMimeType rdf = db.mimeTypeForName(QString::fromLatin1("application/rdf+xml"));
    QVERIFY(rdf.isValid());
    QCOMPARE(rdf.comment(), QString::fromLatin1("RDF file"));

    QMimeType bzip2 = db.mimeTypeForName(QString::fromLatin1("application/x-bzip2"));
    QVERIFY(bzip2.isValid());
    QCOMPARE(bzip2.comment(), QString::fromLatin1("Bzip archive"));

    QMimeType defaultMime = db.mimeTypeForName(QString::fromLatin1("application/octet-stream"));
    QVERIFY(defaultMime.isValid());
    QVERIFY(defaultMime.isDefault());

    QMimeType doesNotExist = db.mimeTypeForName(QString::fromLatin1("foobar/x-doesnot-exist"));
    QVERIFY(!doesNotExist.isValid());

    // TODO move to findByFile
#ifdef Q_OS_LINUX
    QString exePath = QStandardPaths::findExecutable(QLatin1String("ls"));
    if (exePath.isEmpty())
        qWarning() << "ls not found";
    else {
        const QString executableType = QString::fromLatin1("application/x-executable");
        //QTest::newRow("executable") << exePath << executableType;
        QCOMPARE(db.mimeTypeForFile(exePath).name(), executableType);
    }
#endif

}
开发者ID:OniLink,项目名称:Qt5-Rehost,代码行数:48,代码来源:tst_qmimedatabase.cpp

示例15: locateStaticFile

bool StaticSimple::locateStaticFile(Context *c, const QString &relPath)
{
    Q_D(const StaticSimple);

    for (const QDir &includePath : d->includePaths) {
        QString path = includePath.absoluteFilePath(relPath);
        QFileInfo fileInfo(path);
        if (fileInfo.exists()) {
            Response *res = c->res();
            const QDateTime currentDateTime = fileInfo.lastModified();
            if (currentDateTime == c->req()->headers().ifModifiedSinceDateTime()) {
                res->setStatus(Response::NotModified);
                return true;
            }

            QFile *file = new QFile(path);
            if (file->open(QFile::ReadOnly)) {
                qCDebug(C_STATICSIMPLE) << "Serving" << path;
                Headers &headers = res->headers();

                // set our open file
                res->setBody(file);

                QMimeDatabase db;
                // use the extension to match to be faster
                QMimeType mimeType = db.mimeTypeForFile(path, QMimeDatabase::MatchExtension);
                if (mimeType.isValid()) {
                    headers.setContentType(mimeType.name());
                }
                headers.setContentLength(file->size());

                headers.setLastModified(currentDateTime);
                // Tell Firefox & friends its OK to cache, even over SSL
                headers.setHeader(QStringLiteral("Cache-Control"), QStringLiteral("public"));

                return true;
            }

            qCWarning(C_STATICSIMPLE) << "Could not serve" << path << file->errorString();
            return false;
        }
    }

    qCWarning(C_STATICSIMPLE) << "File not found" << relPath;
    return false;
}
开发者ID:buschmann23,项目名称:cutelyst,代码行数:46,代码来源:staticsimple.cpp


注:本文中的QMimeDatabase::mimeTypeForFile方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。