crossplatform.ru

Здравствуйте, гость ( Вход | Регистрация )

 
Ответить в данную темуНачать новую тему
> Помогите плиз разобраться с моделью
Rocky
  опции профиля:
сообщение 6.12.2010, 15:20
Сообщение #1


Старейший участник
****

Группа: Участник
Сообщений: 530
Регистрация: 22.12.2008
Из: Санкт-Петербург
Пользователь №: 463

Спасибо сказали: 22 раз(а)




Репутация:   7  


Всем привет! Вот решил устранить темное для меня на данный момент времени место в Qt - модель/представление. Для теста делаю пример на основании файлов в заданном директории: таблицу, с 4-мя колонками - имя файла, создатель файла, время создания, время модификации. Количество строк - это количество файлов в директории. Вот написал такой класс:
Раскрывающийся текст
#ifndef DIRFILEMODEL_H
#define DIRFILEMODEL_H

#include <QAbstractTableModel>
#include <vector>
#include <QDateTime>

class CDirFileModel : public QAbstractTableModel
{
//--------------------------------------------------------------------------------------------------//
    struct TFile
    {
        TFile(const int& anIndex) : nIndex(anIndex)
        {
        }

        int nIndex;
        QString sFileName;
        QString sFileAuthor;
        QDateTime oCreated;
        QDateTime oModifyed;

        inline bool operator <  (const TFile& rhs) const {return (nIndex < rhs.nIndex);}
        inline bool operator >  (const TFile& rhs) const {return (nIndex > rhs.nIndex);}
        inline bool operator == (const TFile& rhs) const {return nIndex == rhs.nIndex;}
        inline bool operator != (const TFile& rhs) const {return !operator ==(rhs);}
    };
    typedef std::vector<TFile> FileCollection;
//--------------------------------------------------------------------------------------------------//
    FileCollection m_roFiles;

public:
    CDirFileModel();

    virtual QModelIndex index (int row, int column, const QModelIndex & parent = QModelIndex() ) const;
    virtual bool setData (const QModelIndex & index, const QVariant & value, int role = Qt::EditRole);
    virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    virtual Qt::ItemFlags flags(const QModelIndex &index) const;
    virtual int columnCount(const QModelIndex &parent = QModelIndex()) const;
    virtual int rowCount(const QModelIndex &parent = QModelIndex()) const;
    virtual bool insertRows(int row, int count, const QModelIndex & parent = QModelIndex());
    virtual bool removeRows(int row, int count, const QModelIndex& parent);
};

#endif // DIRFILEMODEL_H


Раскрывающийся текст
#include "./DirFileModel.h"

#include <algorithm>

//-----------------------------------------------------------------------------------------//
CDirFileModel::CDirFileModel()
{
}
//-----------------------------------------------------------------------------------------//
QModelIndex CDirFileModel::index (int row, int column, const QModelIndex & /*parent*/) const
{
    return hasIndex(row, column) ? createIndex(row, column, 0) : QModelIndex();
}
//-----------------------------------------------------------------------------------------//
QVariant CDirFileModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.row() >=(int)m_roFiles.size()) return QVariant();
    FileCollection::const_iterator itFile = std::find(m_roFiles.begin(), m_roFiles.end(), TFile(index.row()));
    if (itFile == m_roFiles.end()) return QVariant();

    switch (index.column())
    {
        case 0: return m_roFiles.at(index.row()).sFileName;
        case 1: return m_roFiles.at(index.row()).sFileAuthor;
        case 2: return m_roFiles.at(index.row()).oCreated;
        case 3: return m_roFiles.at(index.row()).oModifyed;
    }
    return QVariant();
}
//-----------------------------------------------------------------------------------------//
bool CDirFileModel::setData (const QModelIndex & index, const QVariant & value, int role)
{
    if (!index.isValid() || index.row() >=(int)m_roFiles.size()) return false;
    FileCollection::iterator itFile = std::find(m_roFiles.begin(), m_roFiles.end(), TFile(index.row()));
    if (itFile == m_roFiles.end()) return false;

    switch (index.column())
    {
        case 0: {itFile->sFileName = value.toString(); return true;}
        case 1: {itFile->sFileAuthor = value.toString(); return true;}
        case 2: {itFile->oCreated = value.toDateTime(); return true;}
        case 3: {itFile->oModifyed = value.toDateTime(); return true;}
    }

    return false;
}
//-----------------------------------------------------------------------------------------//
Qt::ItemFlags CDirFileModel::flags(const QModelIndex &index) const
{
    if (!index.isValid())  return Qt::ItemIsEnabled;
    return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
}
//-----------------------------------------------------------------------------------------//
int CDirFileModel::columnCount(const QModelIndex &/*parent*/) const
{
    return 4;
}
//-----------------------------------------------------------------------------------------//
int CDirFileModel::rowCount(const QModelIndex &/*parent*/) const
{
    return m_roFiles.size();
}
//-----------------------------------------------------------------------------------------//
bool CDirFileModel::insertRows(int row, int count, const QModelIndex & /*parent*/)
{
    beginInsertRows(QModelIndex(), row, row + count - 1);
    for (int nRow = 0; nRow < count; ++nRow)
    {
        m_roFiles.push_back(TFile(row));
    }
    endInsertRows();
    return true;
}
//-----------------------------------------------------------------------------------------//
bool CDirFileModel::removeRows(int row, int count, const QModelIndex& /*parent*/)
{
    beginRemoveRows(QModelIndex(), row, row + count - 1);
    for (int nRow = 0; nRow < count; ++nRow)
    {
        FileCollection::iterator itFile = std::find(m_roFiles.begin(), m_roFiles.end(), TFile(nRow));
        if (itFile != m_roFiles.end()) m_roFiles.erase(itFile);
    }
    endRemoveRows();
    return true;
}
//-----------------------------------------------------------------------------------------//


Пробую заполнить модель данными:
    m_pDirFileModel = new CDirFileModel();
    m_pDirFileModel->insertRows(0, 2);
    QModelIndex oIdx00 = m_pDirFileModel->index(0, 0); m_pDirFileModel->setData(oIdx00, "00");
    QModelIndex oIdx01 = m_pDirFileModel->index(0, 1); m_pDirFileModel->setData(oIdx01, "01");
    QModelIndex oIdx02 = m_pDirFileModel->index(0, 2); m_pDirFileModel->setData(oIdx02, QDateTime::currentDateTime());
    QModelIndex oIdx03 = m_pDirFileModel->index(0, 3); m_pDirFileModel->setData(oIdx03, QDateTime::currentDateTime());

    QModelIndex oIdx10 = m_pDirFileModel->index(1, 0); m_pDirFileModel->setData(oIdx10, "10");
    QModelIndex oIdx11 = m_pDirFileModel->index(1, 1); m_pDirFileModel->setData(oIdx11, "11");
    QModelIndex oIdx12 = m_pDirFileModel->index(1, 2); m_pDirFileModel->setData(oIdx12, QDateTime::currentDateTime());
    QModelIndex oIdx13 = m_pDirFileModel->index(1, 3); m_pDirFileModel->setData(oIdx13, QDateTime::currentDateTime());

    ui.tableView->setModel(m_pDirFileModel);


В итоге вижу заполненную только 1-ю строку таблицы, и больше ничего... И то она выводится так, как будто в ячейках checkBox-ы установлены (только на них не нажать). В чем моя ошибка?

Спасибо)

Сообщение отредактировал Rocky - 6.12.2010, 16:22
Перейти в начало страницы
 
Быстрая цитата+Цитировать сообщение
Rocky
  опции профиля:
сообщение 6.12.2010, 17:14
Сообщение #2


Старейший участник
****

Группа: Участник
Сообщений: 530
Регистрация: 22.12.2008
Из: Санкт-Петербург
Пользователь №: 463

Спасибо сказали: 22 раз(а)




Репутация:   7  


Просто откуда эти некликабельные чекбоксы взялись? :unsure:
Перейти в начало страницы
 
Быстрая цитата+Цитировать сообщение
Litkevich Yuriy
  опции профиля:
сообщение 6.12.2010, 20:31
Сообщение #3


разработчик РЭА
*******

Группа: Сомодератор
Сообщений: 9669
Регистрация: 9.1.2008
Из: Тюмень
Пользователь №: 64

Спасибо сказали: 807 раз(а)




Репутация:   94  


читай внимательно это

Ты в методе setData для любой роли, в том числе Qt::CheckStateRole, что-нибудь да возвращаешь. А нужно проверять роль, для той, которая тебя интересует, нужно вернуть что-то, а для остальных QVariant()

И вот это читай
Перейти в начало страницы
 
Быстрая цитата+Цитировать сообщение
Rocky
  опции профиля:
сообщение 6.12.2010, 23:28
Сообщение #4


Старейший участник
****

Группа: Участник
Сообщений: 530
Регистрация: 22.12.2008
Из: Санкт-Петербург
Пользователь №: 463

Спасибо сказали: 22 раз(а)




Репутация:   7  


Я уже перед уходом с работы сделал все ) Даже вроде со всем разобрался (и как фон ячеек менять тож). Не отписался потому что инет админ вырубил. Спасибо, я это все читал, но бегло. Видимо из-за этого косяки и были. Завтра все равно еще раз подробнее все прочитаю.
Перейти в начало страницы
 
Быстрая цитата+Цитировать сообщение

Быстрый ответОтветить в данную темуНачать новую тему
Теги
Нет тегов для показа


1 чел. читают эту тему (гостей: 1, скрытых пользователей: 0)
Пользователей: 0




RSS Текстовая версия Сейчас: 28.3.2024, 18:12