QTreeView和QFileSystemModel仅显示USB驱动器

时间:2014-12-02 20:05:17

标签: qt qfilesystemmodel

我正在尝试编写一个对话框,允许用户从系统中找到的任何已安装的USB驱动器中进行选择。在Windows中,我可以使用GetLogicalDriveStrings和GetDriveType调用手动获取此信息,因此我可以创建一个简单的列表。但是用户还需要能够向下导航到任何一个USB驱动器,以选择正确的文件夹来写入文件。我已经看了QFileSystemModel,但我没有看到如何限制(过滤)它只显示已安装的USB驱动器及其子文件夹/文件。有没有人知道如何使用Qt框架最好地完成这项工作?


更新 - 12/3/24:

docsteer,谢谢你的建议。听起来这是正确的方式。我实现了建议的更改,并且我在运行应用程序时遇到崩溃。它显示C:,并等待一段时间,然后崩溃,错误代码为255.我认为有些东西我没有在这里正确连接,但还没有能够解决这个问题。那些没有崩溃的时候,我仍然看到系统上可用驱动器的完整列表,包括我插入的两个USB,而不仅仅是看到USB。如果我在filesystemmodeldialog.cpp中更改第42行,以便我传入“dir”而不是“usbModel”,则不会发生崩溃。你或任何人都可以在这里看到任何可能导致崩溃的事情,以及为什么我创建的USBDriveFilterProxyModel正确地从所有已安装的驱动器中选择两个USB,无法过滤视图中的数据?我已经从我的小测试应用程序中提供了所有文件,包括从.ui文件生成的标题,因此如果有人想运行它以查看正在发生的事情,他们可以。

main.cpp中:

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

mainwindow.cpp:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

class FileSystemModelDialog;
class QFileSystemModel;

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    void detectUsb();

private:
    Ui::MainWindow *ui;
    FileSystemModelDialog *treeView;
    QFileSystemModel *fileSystemModel;
};

#endif // MAINWINDOW_H

mainwindow.cpp:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "filesystemmodeldialog.h"

#include <QFileSystemModel>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    treeView = new FileSystemModelDialog(this);
    setCentralWidget(treeView);
    fileSystemModel = new QFileSystemModel;
}

MainWindow::~MainWindow()
{
    delete ui;
}

filesystemmodeldialog.h:

#ifndef FILESYSTEMMODELDIALOG_H
#define FILESYSTEMMODELDIALOG_H

#include "ui_filesystemmodelwidget.h"

#include <QWidget>
#include <QFileSystemModel>
#include <QItemDelegate>

class USBDriveFilterProxyModel;

class IconItemDelegate : public QItemDelegate
{
public:
    IconItemDelegate();
    QSize sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const;
};

class IconFileSystemModel : public QFileSystemModel
{
    Q_OBJECT
public:
    virtual QVariant data ( const QModelIndex & index, int role = Qt::DisplayRole ) const;

};

class FileSystemModelDialog : public QWidget
{
    Q_OBJECT

public:
    explicit FileSystemModelDialog(QWidget *parent);
    ~FileSystemModelDialog();

private:
    Ui::FileSystemModelWidget *ui;
    IconFileSystemModel *dir;
    USBDriveFilterProxyModel *usbModel;

Q_SIGNALS:
    void signalFileSelected(QString);
};

#endif // FILESYSTEMMODELDIALOG_H

filesystemmodeldialog.cpp:

#include "filesystemmodeldialog.h"
#include "usbdrivefilter.h"

IconItemDelegate::IconItemDelegate(){}

QSize IconItemDelegate::sizeHint ( const QStyleOptionViewItem & /*option*/, const QModelIndex & index ) const
{
    const QFileSystemModel *model = reinterpret_cast<const QFileSystemModel *>(index.model());
    QFileInfo info = model->fileInfo(index);
    if(info.isDir())
    {
        return QSize(40,40);
    }
    else
    {
        return QSize(64,64);
    }
}

QVariant IconFileSystemModel::data ( const QModelIndex & index, int role ) const
{
    // will do more, but for now, just paints to view
    return QFileSystemModel::data(index, role);
}

FileSystemModelDialog::FileSystemModelDialog(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FileSystemModelWidget)
{
    ui->setupUi(this);

    dir = new IconFileSystemModel();
    dir->setRootPath("\\");
    dir->setFilter(QDir::AllDirs | QDir::NoDotAndDotDot);

    usbModel = new USBDriveFilterProxyModel(this);
    usbModel->setSourceModel(dir);
    usbModel->setDynamicSortFilter(true);

    IconItemDelegate *iconItemDelegate = new IconItemDelegate();

    ui->treeView->setModel(usbModel);
    // hide unneeded hierachy info columns
    ui->treeView->hideColumn(1);
    ui->treeView->hideColumn(2);
    ui->treeView->hideColumn(3);
    ui->treeView->setItemDelegate(iconItemDelegate);
}

FileSystemModelDialog::~FileSystemModelDialog()
{
    delete dir;
}

usbdrivefilter.h:

#ifndef USBDRIVEFILTER_H
#define USBDRIVEFILTER_H

#include <QSortFilterProxyModel>
#include <QModelIndex>
#include <QString>

class USBDriveFilterProxyModel : public QSortFilterProxyModel
{
    Q_OBJECT
public:
    explicit USBDriveFilterProxyModel(QObject *parent = 0);

protected:
    virtual bool filterAcceptsRow(
        int source_row, const QModelIndex &source_parent) const;

private:
    void getMountedRemovables();

private:
    QList<QString> removables;

};

#endif // USBDRIVEFILTER_H

usbdrivefilter.cpp:

#include "usbdrivefilter.h"

#include <windows.h>

USBDriveFilterProxyModel::USBDriveFilterProxyModel(QObject *parent) :
    QSortFilterProxyModel(parent)
{
    getMountedRemovables();
    // will eventually also register for changes to mounted removables
    // but need to get passed my current issue of not displaying only USBs.
}

bool USBDriveFilterProxyModel::filterAcceptsRow(int sourceRow,
    const QModelIndex &sourceParent) const
{
    QModelIndex index0 = sourceModel()->index(sourceRow, 0, sourceParent);

    // Since drive string can have more than just "<DriveLetter>:", need
    // to check each entry in the usb list for whether it is contained in
    // the current drive string.

    for (int i = 0; i < removables.size(); i++)
    {
        if (sourceModel()->data(index0).toString().contains(removables[i]))
        {
            return true;
        }
    }
    return false;
}

void USBDriveFilterProxyModel::getMountedRemovables()
{
    DWORD test = GetLogicalDrives();

    DWORD mask = 1;
    UINT type = 0;
    WCHAR wdrive[] = L"C:\\"; // use as a drive letter template
    for (int i = 0; i < 32; i++)
    {
        if (test & mask)
        {
            wdrive[0] = (char)('A' + i); // change letter in template
            type = GetDriveType(wdrive);
            switch (type) {
            case DRIVE_REMOVABLE:
            {
                QString qdrive = QString((char)('A' + i)) + ":";
                removables.append(qdrive);
                break;
            }
            default: break;
            }
        }
        mask = mask << 1;
    }
}

ui_filesystemmodelwidget.h:

#ifndef UI_FILESYSTEMMODELWIDGET_H
#define UI_FILESYSTEMMODELWIDGET_H

#include <QtWidgets/QApplication>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QTreeView>

QT_BEGIN_NAMESPACE

class Ui_FileSystemModelWidget
{
public:
    QTreeView *treeView;

    void setupUi(QWidget *FileSystemModelWidget)
    {
        if (FileSystemModelWidget->objectName().isEmpty())
            FileSystemModelWidget->setObjectName(QStringLiteral("FileSystemModelWidget"));
        FileSystemModelWidget->resize(670, 755);
        treeView = new QTreeView(FileSystemModelWidget);
        treeView->setGeometry(QRect(0, 0, 670, 531));
        treeView->setObjectName(QStringLiteral("treeView"));
        treeView->setAutoFillBackground(true);
        treeView->setStyleSheet(QLatin1String(" QScrollBar:vertical {\n"
"      width: 61px;\n"
"   background-color: rgb(227, 227, 227);\n"
"  }\n"
"  QScrollBar::handle:vertical {\n"
"      min-height: 50px;\n"
"  }\n"
"\n"
"QTreeView, QListView {\n"
"   alternate-background-color: rgb(226, 226, 226);\n"
"   font-size: 16px;\n"
"     show-decoration-selected: 1;\n"
" }\n"
"\n"
" QTreeView::item, QListView::item {\n"
" height: 22px;\n"
"      border: 1px solid transparent;\n"
"     border-top-color: transparent;\n"
"     border-bottom-color: transparent;\n"
" }\n"
"\n"
" QTreeView::item:selected, QListView::item::selected {\n"
"     border: 1px solid #567dbc;\n"
"   background-color: rgb(85, 170, 255);\n"
" }\n"
"\n"
"\n"
" QTreeView::branch:has-siblings:!adjoins-item {\n"
"     border-image: url(:/new/prefix1/images/vline.png) 0;\n"
" }\n"
"\n"
" QTreeView::branch:has-siblings:adjoins-item {\n"
"     border-image: url(:/new/prefix1/images/branch-more.png) 0;\n"
" }\n"
"\n"
" QTreeView::branch:!has-children:!has-siblings:adjoins-item {\n"
"     border-image: url"
                        "(:/new/prefix1/images/branch-end.png) 0;\n"
" }\n"
"\n"
" QTreeView::branch:has-children:!has-siblings:closed,\n"
" QTreeView::branch:closed:has-children:has-siblings {\n"
"         border-image: none;\n"
"         image: url(:/new/prefix1/images/branch-closed.png);\n"
" }\n"
"\n"
" QTreeView::branch:open:has-children:!has-siblings,\n"
" QTreeView::branch:open:has-children:has-siblings  {\n"
"         border-image: none;\n"
"         image: url(:/new/prefix1/images/branch-open.png);\n"
" }\n"
""));
        treeView->setFrameShape(QFrame::Box);
        treeView->setFrameShadow(QFrame::Plain);
        treeView->setHorizontalScrollMode(QAbstractItemView::ScrollPerItem);
        treeView->setExpandsOnDoubleClick(true);
        treeView->header()->setVisible(false);
        treeView->header()->setStretchLastSection(true);

        retranslateUi(FileSystemModelWidget);

        QMetaObject::connectSlotsByName(FileSystemModelWidget);
    } // setupUi

    void retranslateUi(QWidget *FileSystemModelWidget)
    {
        FileSystemModelWidget->setWindowTitle(QApplication::translate("FileSystemModelWidget", "Form", 0));
    } // retranslateUi

};

namespace Ui {
    class FileSystemModelWidget: public Ui_FileSystemModelWidget {};
} // namespace Ui

QT_END_NAMESPACE

#endif // UI_FILESYSTEMMODELWIDGET_H

更新 - 12/4/24:

所以我发现崩溃发生在filesystemusbmodeldialog.cpp文件中的IconItemDelegate :: sizeHint()中。跑步到第9行:

QFileInfo info = model->fileInfo(index);

并在此时单步执行会导致访问冲突。我假设这是因为我将FileFileSystemUsbModel对象替换为USBDriveFilterProxyModel作为FileSystemUsbModelDialog构造函数中的QTreeView模型。因此我假设在IconItemDelegate :: sizeHint()中转换index.model()是一个不正确的强制转换,我现在需要在调用fileInfo()之前获取原始源模型。所以我将sizeHint()重载更改为以下内容:

QSize IconItemUsbDelegate::sizeHint ( const QStyleOptionViewItem & /*option*/, const QModelIndex & index ) const
{
    const USBDriveFilterProxyModel *model = reinterpret_cast<const USBDriveFilterProxyModel *>(index.model());
    const QFileSystemModel *fsmodel = reinterpret_cast<const QFileSystemModel *>(model->sourceModel());
    QFileInfo info = fsmodel->fileInfo(index);
    if(info.isDir())
    {
        return QSize(40,40);
    }
    else
    {
        return QSize(64,64);
    }
}

但那没用。然后我发现了一个链接似乎说我需要在我的视图上调用setRootIndex(),现在代理代替了模型,所以我在我的FileSystemUsbModelDialog构造函数中添加了它,现在看起来像这样:

FileSystemUsbModelDialog::FileSystemUsbModelDialog(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FileSystemUsbModelWidget)
{
    ui->setupUi(this);

    dir = new IconFileSystemUsbModel();
    dir->setRootPath("\\");
    dir->setFilter(QDir::AllDirs | QDir::NoDotAndDotDot);

    usbModel = new USBDriveFilterProxyModel(this);
    usbModel->setSourceModel(dir);
    usbModel->setDynamicSortFilter(false);

    IconItemUsbDelegate *iconItemDelegate = new IconItemUsbDelegate();

    ui->treeView->setModel(usbModel);
    ui->treeView->setRootIndex(usbModel->mapFromSource(dir->setRootPath("\\")));
    // hide unneeded hierachy info columns
    ui->treeView->hideColumn(1);
    ui->treeView->hideColumn(2);
    ui->treeView->hideColumn(3);
    ui->treeView->setItemDelegate(iconItemDelegate);
}

这不起作用。我回到我的IconItemUsbDelegate :: sizeHint()并将其更改回来,以为可能在视图上设置root是我真正需要做的,而且没有运气。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

我建议使用QSortFilterProxyModel进行此操作。示例可能看起来像

.header

class USBDriveFilter : public QSortFilterProxyModel
{
    Q_OBJECT;
public:
    USBDriveFilter(QObject *parent = 0);
protected:
    // Reimplemented from QSortFilterProxyModel
    virtual bool filterAcceptsRow ( int source_row, const QModelIndex & source_parent ) const;
};

的.cpp

bool USBDriveFilter::filterAcceptsRow(int sourceRow,
         const QModelIndex &sourceParent) const
{
    QModelIndex index0 = sourceModel()->index(sourceRow, 0, sourceParent);
    // This is a naive example and just doesn't accept the drive if the name
    // of the root node contains C: - you should extend it to check the letter
    // against your known list of USB drives derived from the windows API
    return (!sourceModel()->data(index0).toString().contains("C:"));
}

要使用此功能,您可以执行类似

的操作
QFileSystemModel *m = new QFileSystemModel(this);
USBDriveFilter *filter = new USBDriveFilter(this);
filter->setSourceModel(m);
// Now use filter as your model to pass into your tree view.

答案 1 :(得分:0)

所以docsteer让我走上正轨,正如我在更新中所述,但正如我所说,进入我的项目委托的sizeHint()方法时遇到了崩溃。根据其他人的建议,我将一些调试语句放入以查明索引显示的内容如下:

qDebug() << index.isValid();
qDebug() << "text = " <<  index.data();
qDebug() << "Row = " << index.row()  << "Column = " << index.column();

我发现索引的内容特定于我希望代理模型包含的内容,而不是文件系统模型。仔细观察,我意识到我已经将与代理模型相关联的索引传递到fileInfo()方法,以便转换为文件系统模型。我改变它如下所示,以便我首先将索引模型转换为代理模型类型的指针,然后从中获取源(文件系统)模型指针并调用其fileInfo()方法。但是现在我首先将索引映射到源索引,然后将该映射的结果传递给文件系统模型的fileInfo()方法,该方法现在就像魅力一样:

const USBDriveFilterProxyModel *model = reinterpret_cast<const USBDriveFilterProxyModel *>(index.model());
const QFileSystemModel *fsmodel = reinterpret_cast<const QFileSystemModel *>(model->sourceModel());
QFileInfo info = fsmodel->fileInfo(index);
if(info.isDir())
{
    return QSize(40,40);
}
else
{
    return QSize(64,64);
}

感谢您的帮助。