3

有必要在 QListView 中通过图标和复选框按给定路径列出目录,然后将标记文件夹的名称传输到程序。对于列表目录,我使用代码:

#include <QtGui/QApplication>
#include <QFileSystemModel>
#include <QListView>


    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);

        QFileSystemModel model;

        QListView listView;
        listView.setModel(&model);
        listView.setRootIndex(model.setRootPath("C:\\Program Files"));
        listView.show();

        return a.exec();
    }

按下按钮后如何添加复选框并传输?

谢谢。

4

1 回答 1

1

没有什么可以做的只是几行代码。您可以派生QFileSystemModel并添加一个复选框列,也可以创建一个代理模型来执行相同的操作。

请注意,您可以使用内置的选择机制来 Ctrl-click/⌘-click 以将选择扩展到多个项目:

//main.cpp
#include <QApplication>
#include <QFileSystemModel>
#include <QGridLayout>
#include <QListView>
#include <QPushButton>
#include <QMessageBox>

class Win : public QWidget
{
    Q_OBJECT
    QListView * view;
    QPushButton * button;
public:
    Win(QAbstractItemModel * model, const QModelIndex & idx) :
        view(new QListView(this)), button(new QPushButton("List Selection", this))
    {
        QGridLayout * lay = new QGridLayout;
        lay->addWidget(view, 0, 0, 1, 2);
        lay->addWidget(button, 1, 0);
        setLayout(lay);
        view->setSelectionMode(QAbstractItemView::MultiSelection);
        view->setModel(model);
        view->setRootIndex(idx);
        connect(button, SIGNAL(clicked()), SLOT(showSelection()));
    }
public slots:
    void showSelection() {
        QString str;
        foreach (QModelIndex i, view->selectionModel()->selectedIndexes()) {
            str.append(i.data().toString());
            str.append("\n");
        }
        QMessageBox::information(this, "Selected items", str);
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QFileSystemModel model;
    Win v(&model, model.setRootPath("/"));
    v.show();
    return a.exec();
}

#include "main.moc"
于 2012-06-28T13:28:28.280 回答