Большой набор данных в QTableView - PullRequest
0 голосов
/ 16 февраля 2020

Я пытаюсь добавить большие наборы данных в QTableView. Поскольку существует огромный набор данных, чтобы избежать зависания приложения, я пытаюсь использовать QAbstractTableModel, чтобы не показывать сразу весь набор данных, а только то, что необходимо. Основываясь на примере QT для этого ( ЗДЕСЬ ), у меня есть следующий класс: FileListModel. cpp

#include "filelistmodel.h"

#include <QGuiApplication>
#include <QDir>
#include <QPalette>
#include "qdebug.h"

FileListModel::FileListModel(QObject *parent)
    : QAbstractTableModel(parent), fileCount(0) //edit
{}

int FileListModel::rowCount(const QModelIndex &parent) const
{
    return parent.isValid() ? 0 : fileCount;
}

QVariant FileListModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
    {
        return QVariant();
    }
    if (index.row() >= fileList.size() || index.row() < 0)
    {
        return QVariant();
    }
    if (role == Qt::DisplayRole)
    {
        return fileList.at(index.row());
    }
    return QVariant();
}

bool FileListModel::canFetchMore(const QModelIndex &parent) const
{
    if (parent.isValid())
    {
        return false;
    }
    return (fileCount < fileList.size());
}
int FileListModel::columnCount(const QModelIndex &parent) const
{
    return parent.isValid() ? 0 : colCount;
}
void FileListModel::fetchMore(const QModelIndex &parent)
{
    if (parent.isValid())
    {
        return;
    }
    int remainder = fileList.size() - fileCount;
    int itemsToFetch = qMin(100, remainder);

    if (itemsToFetch <= 0)
    {
        return;
    }
    beginInsertRows(QModelIndex(), fileCount, fileCount + itemsToFetch - 1);
    qDebug()<< "Qmodelindex "<< QModelIndex()<< "filecount "<< fileCount <<"filecount + itemtofetch "<<fileCount + itemsToFetch - 1;
    fileCount += itemsToFetch;

    endInsertRows();
}
void FileListModel::setColumnNumber(const int x) //edit
{
    colCount = x;
}
void FileListModel::setDataToList(const QList<float> &data)
{
    beginResetModel();
    fileList = data;
    fileCount = 0;
    endResetModel();
}

FileListModel.h

#ifndef FILELISTMODEL_H
#define FILELISTMODEL_H

#include <QAbstractTableModel>
#include <QStringList>

class FileListModel : public QAbstractTableModel //edit
{
    Q_OBJECT

public:
    FileListModel(QObject *parent = nullptr);

    int rowCount(const QModelIndex &parent = QModelIndex()) const override;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
    int columnCount(const QModelIndex &parent = QModelIndex()) const override; //edit
    void setColumnNumber(const int );

public slots:
    void setDataToList(const QList<float>&);

protected:
    bool canFetchMore(const QModelIndex &parent) const override;
    void fetchMore(const QModelIndex &parent) override;

private:
    QList<float> fileList;
    int fileCount;
int colCount;//edit
};

#endif // FILELISTMODEL_H

В моем окне у меня есть QTableView и 5 QList<float>, каждый из которых представляет столбец. Я продолжаю таким образом, чтобы добавить данные в мой QTableView:

FileListModel *model=new FileListModel(this);
model->setColumnNumber(5); //edit

model->setDataToList(list1);
model->setDataToList(list2);
model->setDataToList(list3);
model->setDataToList(list4);
model->setDataToList(list5);

tableview->setModel(model)

Однако последний добавленный список (list5) заменяет предыдущий, и у меня во всех столбцах только один и тот же текст. Я знаю, что мне нужно написать необходимый код для добавления столбцов. Но, честно говоря, я не очень хорошо знаю классы QAbstract и не знаю, как поступить. Я был бы признателен, если бы вы могли дать мне несколько советов или пример того, как изменить мой код, чтобы добавить столбцы в мою модель.

1 Ответ

0 голосов
/ 16 февраля 2020

Я нашел, как поступить, сохранив мои данные в QList>. Ниже приведен рабочий код, который, вероятно, можно улучшить:

CPP ФАЙЛ

#include "filelistmodel.h"

#include <QGuiApplication>
#include <QDir>
#include <QPalette>
#include "qdebug.h"

FileListModel::FileListModel(QObject *parent)
    : QAbstractTableModel(parent), rowNumber(0)
{}

int FileListModel::rowCount(const QModelIndex &parent) const
{
    return parent.isValid() ? 0 : rowNumber;
}

int FileListModel::columnCount(const QModelIndex &parent) const
{
    return parent.isValid() ? 0 : colNumber;
}

void FileListModel::setColumnNumber(const int x)
{
    colNumber = x;
}

QVariant FileListModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
    {
        return QVariant();
    }
    if (index.row() >= fileList[0].size() || index.row() < 0)
    {
        return QVariant();
    }
    if (role == Qt::DisplayRole)
    {
        return fileList[index.column()][index.row()];
    }
    return QVariant();
}

bool FileListModel::canFetchMore(const QModelIndex &parent) const
{
    if (parent.isValid())
    {
        return false;
    }
    return (rowNumber < fileList[0].size());
}

void FileListModel::fetchMore(const QModelIndex &parent)
{
    if (parent.isValid())
    {
        return;
    }
    int remainder = fileList[0].size() - rowNumber;
    int itemsToFetch = qMin(100, remainder);

    if (itemsToFetch <= 0)
    {
        return;
    }
    beginInsertRows(QModelIndex(), rowNumber, rowNumber + itemsToFetch - 1);

    rowNumber += itemsToFetch;

    endInsertRows();
}

void FileListModel::setDataToTable(const QList<QList<float>> &data)
{
    beginResetModel();
    fileList = data;
    rowNumber = 0;
    endResetModel();
}

H ФАЙЛ

#ifndef FILELISTMODEL_H
#define FILELISTMODEL_H

#include <QAbstractListModel>
#include <QStringList>

class FileListModel : public QAbstractTableModel
{
    Q_OBJECT

public:
    FileListModel(QObject *parent = nullptr);

    int rowCount(const QModelIndex &parent = QModelIndex()) const override;
    int columnCount(const QModelIndex &parent = QModelIndex()) const override;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
    void setColumnNumber(const int );
    void setDataToTable(const QList<QList<float>>&);

protected:
    bool canFetchMore(const QModelIndex &parent) const override;
    void fetchMore(const QModelIndex &parent) override;

private:
    QList<QList<float>> fileList;
    int rowNumber;
    int colNumber;
};

#endif // FILELISTMODEL_H

СТРОИТЕЛЬНАЯ МОДЕЛЬ

FileListModel *pModel =new FileListModel(this);
QList<QList<float>> a;
pModel->setColumnNumber(5);
a.append(qlist1);
a.append(qlist2);
a.append(qlist3);
a.append(qlist4);
a.append(qlist5);
pModel->setDataToTable(a);
...