⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 qdirmodel.cpp

📁 奇趣公司比较新的qt/emd版本
💻 CPP
📖 第 1 页 / 共 3 页
字号:
/******************************************************************************** Copyright (C) 1992-2007 Trolltech ASA. All rights reserved.**** This file is part of the QtGui module of the Qt Toolkit.**** This file may be used under the terms of the GNU General Public** License version 2.0 as published by the Free Software Foundation** and appearing in the file LICENSE.GPL included in the packaging of** this file.  Please review the following information to ensure GNU** General Public Licensing requirements will be met:** http://trolltech.com/products/qt/licenses/licensing/opensource/**** If you are unsure which license is appropriate for your use, please** review the following information:** http://trolltech.com/products/qt/licenses/licensing/licensingoverview** or contact the sales department at sales@trolltech.com.**** In addition, as a special exception, Trolltech gives you certain** additional rights. These rights are described in the Trolltech GPL** Exception version 1.0, which can be found at** http://www.trolltech.com/products/qt/gplexception/ and in the file** GPL_EXCEPTION.txt in this package.**** In addition, as a special exception, Trolltech, as the sole copyright** holder for Qt Designer, grants users of the Qt/Eclipse Integration** plug-in the right for the Qt/Eclipse Integration to link to** functionality provided by Qt Designer and its related libraries.**** Trolltech reserves all rights not expressly granted herein.**** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.******************************************************************************/#include "qdirmodel.h"#ifndef QT_NO_DIRMODEL#include <qstack.h>#include <qfile.h>#include <qurl.h>#include <qmime.h>#include <qpair.h>#include <qvector.h>#include <qobject.h>#include <qdatetime.h>#include <qlocale.h>#include <qstyle.h>#include <qapplication.h>#include <private/qabstractitemmodel_p.h>#include <qdebug.h>/*!    \enum QDirModel::Roles    \value FileIconRole    \value FilePathRole    \value FileNameRole*/class QDirModelPrivate : public QAbstractItemModelPrivate{    Q_DECLARE_PUBLIC(QDirModel)public:    struct QDirNode    {        QDirNode() : parent(0), populated(false), stat(false) {}        ~QDirNode() { children.clear(); }        QDirNode *parent;        QFileInfo info;        QIcon icon; // cache the icon        mutable QVector<QDirNode> children;        mutable bool populated; // have we read the children        mutable bool stat;    };    QDirModelPrivate()        : resolveSymlinks(true),          readOnly(true),          lazyChildCount(false),          allowAppendChild(true),          iconProvider(&defaultProvider),          shouldStat(true) // ### This is set to false by QFileDialog    { }    void init();    QDirNode *node(int row, QDirNode *parent) const;    QVector<QDirNode> children(QDirNode *parent, bool stat) const;    void _q_refresh();    void savePersistentIndexes();    void restorePersistentIndexes();    QFileInfoList entryInfoList(const QString &path) const;    QStringList entryList(const QString &path) const;    QString name(const QModelIndex &index) const;    QString size(const QModelIndex &index) const;    QString type(const QModelIndex &index) const;    QString time(const QModelIndex &index) const;    void appendChild(QDirModelPrivate::QDirNode *parent, const QString &path) const;    static QFileInfo resolvedInfo(QFileInfo info);    inline QDirNode *node(const QModelIndex &index) const;    inline void populate(QDirNode *parent) const;    inline void clear(QDirNode *parent) const;    void invalidate();    mutable QDirNode root;    bool resolveSymlinks;    bool readOnly;    bool lazyChildCount;    bool allowAppendChild;    QDir::Filters filters;    QDir::SortFlags sort;    QStringList nameFilters;    QFileIconProvider *iconProvider;    QFileIconProvider defaultProvider;    QList< QPair<QString,int> > savedPaths;    QList< QPersistentModelIndex > savedPersistentIndexes;    QPersistentModelIndex toBeRefreshed;    bool shouldStat; // use the "carefull not to stat directories" mode};void qt_setDirModelShouldNotStat(QDirModelPrivate *modelPrivate){    modelPrivate->shouldStat = false;}QDirModelPrivate::QDirNode *QDirModelPrivate::node(const QModelIndex &index) const{    QDirModelPrivate::QDirNode *n =        static_cast<QDirModelPrivate::QDirNode*>(index.internalPointer());    Q_ASSERT(n);    return n;}void QDirModelPrivate::populate(QDirNode *parent) const{    Q_ASSERT(parent);    parent->children = children(parent, parent->stat);    parent->populated = true;}void QDirModelPrivate::clear(QDirNode *parent) const{     Q_ASSERT(parent);     parent->children.clear();     parent->populated = false;}void QDirModelPrivate::invalidate(){    QStack<const QDirNode*> nodes;    nodes.push(&root);    while (!nodes.empty()) {        const QDirNode *current = nodes.pop();        current->stat = false;        const QVector<QDirNode> children = current->children;        for (int i = 0; i < children.count(); ++i)            nodes.push(&children.at(i));    }}/*!  \class QDirModel qdirmodel.h  \brief The QDirModel class provides a data model for the local filesystem.  \ingroup model-view  This class provides access to the local filesystem, providing functions  for renaming and removing files and directories, and for creating new  directories. In the simplest case, it can be used with a suitable display  widget as part of a browser or filer.  QDirModel keeps a cache with file information. The cache needs to be  updated with refresh().  A directory model that displays the contents of a default directory  is usually constructed with a parent object:  \quotefromfile snippets/shareddirmodel/main.cpp  \skipto QDirModel *model  \printuntil QDirModel *model  A tree view can be used to display the contents of the model  \skipto QTreeView *tree  \printuntil tree->setModel(  and the contents of a particular directory can be displayed by  setting the tree view's root index:  \printuntil tree->setRootIndex(  The view's root index can be used to control how much of a  hierarchical model is displayed. QDirModel provides a convenience  function that returns a suitable model index for a path to a  directory within the model.  QDirModel can be accessed using the standard interface provided by  QAbstractItemModel, but it also provides some convenience functions that are  specific to a directory model.  The fileInfo(), isDir(), name(), and path() functions provide information  about the underlying files and directories related to items in the model.  Directories can be created and removed using mkdir(), rmdir(), and the  model will be automatically updated to take the changes into account.  \sa nameFilters(), setFilter(), filter(), QListView, QTreeView,      {Dir View Example}, {Model Classes}*//*!    Constructs a new directory model with the given \a parent.    Only those files matching the \a nameFilters and the    \a filters are included in the model. The sort order is given by the    \a sort flags.*/QDirModel::QDirModel(const QStringList &nameFilters,                     QDir::Filters filters,                     QDir::SortFlags sort,                     QObject *parent)    : QAbstractItemModel(*new QDirModelPrivate, parent){    Q_D(QDirModel);    // we always start with QDir::drives()    d->nameFilters = nameFilters.isEmpty() ? QStringList(QLatin1String("*")) : nameFilters;    d->filters = filters;    d->sort = sort;    d->root.parent = 0;    d->root.info = QFileInfo();    d->clear(&d->root);}/*!  Constructs a directory model with the given \a parent.*/QDirModel::QDirModel(QObject *parent)    : QAbstractItemModel(*new QDirModelPrivate, parent){    Q_D(QDirModel);    d->init();}/*!    \internal*/QDirModel::QDirModel(QDirModelPrivate &dd, QObject *parent)    : QAbstractItemModel(dd, parent){    Q_D(QDirModel);    d->init();}/*!  Destroys this directory model.*/QDirModel::~QDirModel(){}/*!  Returns the model item index for the item in the \a parent with the  given \a row and \a column.*/QModelIndex QDirModel::index(int row, int column, const QModelIndex &parent) const{    Q_D(const QDirModel);    // note that rowCount does lazy population    if (column < 0 || column >= 4 || row < 0 || parent.column() > 0)        return QModelIndex();    // make sure the list of children is up to date    QDirModelPrivate::QDirNode *p = (d->indexValid(parent) ? d->node(parent) : &d->root);    Q_ASSERT(p);    if (!p->populated)        d->populate(p); // populate without stat'ing    if (row >= p->children.count())        return QModelIndex();    // now get the internal pointer for the index    QDirModelPrivate::QDirNode *n = d->node(row, d->indexValid(parent) ? p : 0);    Q_ASSERT(n);    return createIndex(row, column, n);}/*!  Return the parent of the given \a child model item.*/QModelIndex QDirModel::parent(const QModelIndex &child) const{    Q_D(const QDirModel);    if (!d->indexValid(child))	return QModelIndex();    QDirModelPrivate::QDirNode *node = d->node(child);    QDirModelPrivate::QDirNode *par = (node ? node->parent : 0);    if (par == 0) // parent is the root node	return QModelIndex();    // get the parent's row    const QVector<QDirModelPrivate::QDirNode> children =        par->parent ? par->parent->children : d->root.children;    Q_ASSERT(children.count() > 0);    int row = (par - &(children.at(0)));    Q_ASSERT(row >= 0);    return createIndex(row, 0, par);}/*!  Returns the number of rows in the \a parent model item.*/int QDirModel::rowCount(const QModelIndex &parent) const{    Q_D(const QDirModel);    if (parent.column() > 0)        return 0;    if (!parent.isValid()) {        if (!d->root.populated) // lazy population            d->populate(&d->root);        return d->root.children.count();    }    if (parent.model() != this)        return 0;    QDirModelPrivate::QDirNode *p = d->node(parent);    if (p->info.isDir() && !p->populated) // lazy population        d->populate(p);    return p->children.count();}/*!  Returns the number of columns in the \a parent model item.*/int QDirModel::columnCount(const QModelIndex &parent) const{    if (parent.column() > 0)        return 0;    return 4;}/*!  Returns the data for the model item \a index with the given \a role.*/QVariant QDirModel::data(const QModelIndex &index, int role) const{    Q_D(const QDirModel);    if (!d->indexValid(index))        return QVariant();    if (role == Qt::DisplayRole || role == Qt::EditRole) {        switch (index.column()) {        case 0: return d->name(index);        case 1: return d->size(index);        case 2: return d->type(index);        case 3: return d->time(index);        default:            qWarning("data: invalid display value column %d", index.column());            return QVariant();        }    }    if (index.column() == 0) {        if (role == FileIconRole)            return fileIcon(index);        if (role == FilePathRole)            return filePath(index);        if (role == FileNameRole)            return fileName(index);    }    if (index.column() == 1 && Qt::TextAlignmentRole == role) {        return Qt::AlignRight;    }    return QVariant();}/*!  Sets the data for the model item \a index with the given \a role to  the data referenced by the \a value. Returns true if successful;  otherwise returns false.  \sa Qt::ItemDataRole*/bool QDirModel::setData(const QModelIndex &index, const QVariant &value, int role){    Q_D(QDirModel);    if (!d->indexValid(index) || index.column() != 0        || (flags(index) & Qt::ItemIsEditable) == 0 || role != Qt::EditRole)        return false;    QDirModelPrivate::QDirNode *node = d->node(index);    QDir dir = node->info.dir();    QString name = value.toString();    if (dir.rename(node->info.fileName(), name)) {        node->info = QFileInfo(dir, name);        QModelIndex sibling = index.sibling(index.row(), 3);        emit dataChanged(index, sibling);        d->toBeRefreshed = index.parent();        int slot = metaObject()->indexOfSlot("_q_refresh()");        QApplication::postEvent(this, new QMetaCallEvent(slot));        return true;    }    return false;}/*!  Returns the data stored under the given \a role for the specified \a section  of the header with the given \a orientation.*/QVariant QDirModel::headerData(int section, Qt::Orientation orientation, int role) const{    if (orientation == Qt::Horizontal) {        if (role != Qt::DisplayRole)            return QVariant();	switch (section) {        case 0: return tr("Name");        case 1: return tr("Size");        case 2: return#ifdef Q_OS_MAC                       tr("Kind", "Match OS X Finder");#else                       tr("Type", "All other platforms");#endif        // Windows   - Type        // OS X      - Kind        // Konqueror - File Type        // Nautilus  - Type        case 3: return tr("Date Modified");        default: return QVariant();        }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -