2

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


更新 - 24 年 12 月 3 日:

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

主.cpp:

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

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

    return a.exec();
}

主窗口.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

主窗口.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;
}

文件系统模型对话框.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

文件系统模型对话框.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

更新 - 24 年 12 月 4 日:

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

QFileInfo info = model->fileInfo(index);

并且在那一点上跨过会导致访问冲突。我假设这是因为我在 FileSystemUsbModelDialog 构造函数中将 IconFileSystemUsbModel 对象替换为 USBDriveFilterProxyModel 作为 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 是我真正需要做的,但没有运气。

有什么想法吗?

4

2 回答 2

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.
于 2014-12-02T22:20:46.607 回答
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);
}

谢谢您的帮助。

于 2014-12-10T13:46:10.220 回答