Помощь - Поиск - Пользователи - Календарь
Полная версия этой страницы: QListView с чекбоксами
Форум на CrossPlatform.RU > Библиотеки > Qt > Qt GUI
Robin Bobin
Нужно вывести список папок директории, после чего выбрать нужные чекбоксами и передать их имена в программу(пути не обязательно). гуглил, но не осилил примеры. Чекбоксы нужны при использовании QFileSystemModel. Как без QFileSystemModel более-менее понятно, но тогда придется вручную выбирать имена папок и ставить иконки. Вот код, который я использую для вывода списка директорий.


#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();
}


Подскажите, кто сталкивался. Спасибо.
balbes
Тебе нужно переопределить QFileSystemModel, нашел пример переопределения:
"CustomFileSystemModel.h"
#ifndef CUSTOMFILESYSTEMMODEL_H_
#define CUSTOMFILESYSTEMMODEL_H_

#include <QFileSystemModel>
#include <QStringList>

class CustomFileSystemModel: public QFileSystemModel
{
    Q_OBJECT

private:
    /// key is the FilePathRole (defined in QFileSystemModel)
    QStringList directories;

public:
    CustomFileSystemModel(QObject *parent);

    ~CustomFileSystemModel();

    inline QStringList getCheckedDirectories() const { return directories; }

    Qt::ItemFlags flags(const QModelIndex& index) const;

    QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;

    bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole);

    bool canFetchMore(const QModelIndex & parent) const;

private:
    void fetch(const QModelIndex &index, const QVariant& value);
};

#endif /* CUSTOMFILESYSTEMMODEL_H_ */


"CustomFileSystemModel.cpp"
#include "CustomFileSystemModel.h"

#include <iostream>
using namespace std;

CustomFileSystemModel::CustomFileSystemModel(QObject *parent)
    : QFileSystemModel(parent)
{
    setReadOnly(true);
    setFilter(QDir::NoDotAndDotDot | QDir::AllDirs | QDir::Files);
}

Qt::ItemFlags CustomFileSystemModel::flags(const QModelIndex& index) const
{
    Qt::ItemFlags f = QFileSystemModel::flags(index);
    if (index.column() == 0) { // make the first column checkable
        /*if (isDir(index)) {
            cout << "dir" << endl;
            //
        } else {
            cout << "file" << endl;
        }*/
        f |= Qt::ItemIsUserCheckable;
    }
    return f;
}

QVariant CustomFileSystemModel::data(const QModelIndex& index, int role) const
{
    if (index.isValid() && index.column() == 0 && role == Qt::CheckStateRole) {
        // the item is checked only if we have stored its path
        return (directories.contains(filePath(index)) ? Qt::Checked : Qt::Unchecked);
    }
    return QFileSystemModel::data(index, role);
}

bool CustomFileSystemModel::setData(const QModelIndex& i, const QVariant& value, int role)
{
    if (i.isValid() && i.column() == 0 && role == Qt::CheckStateRole) {
        // store checked paths, remove unchecked paths
        if (isDir(i)) {
            if (value.toInt() == Qt::Checked) {
                directories << filePath(i);
                cout << hasChildren(i) << endl;
                fetchMore(i);
                fetch(i, Qt::Checked);

            } else {
                directories.removeAll(filePath(i));
                fetch(i, Qt::Unchecked);
            }
            directories.sort();
        }
        return true;
    }
    return QFileSystemModel::setData(i, value, role);
}


void CustomFileSystemModel::fetch(const QModelIndex &i, const QVariant& value)
{
    if (hasChildren(i)) {
        int childCount = rowCount(i);
        cout << "childCount: " << childCount << endl;
        for (int c=0; c<childCount; c++) {
            const QModelIndex child = index(c, 0, i);
            cout << "isValid:" << child.isValid() << endl;
            if (child.isValid()) {
                cout << filePath(child).toStdString() << endl;
                setData(child, value, Qt::CheckStateRole);
            }
        }
    }
}

bool CustomFileSystemModel::canFetchMore(const QModelIndex & parent) const
{
    //bool b = QFileSystemModel::canFetchMore(parent);
    //cout << "canFetchMore: " << b << endl;
    //return hasChildren(parent);
    return true;
}

CustomFileSystemModel::~CustomFileSystemModel()
{

}
К этому примеру нужно только добавить обработку QAbstractItemModel::dataChanged
Для просмотра полной версии этой страницы, пожалуйста, пройдите по ссылке.
Форум IP.Board © 2001-2024 IPS, Inc.