Russian Qt Forum
Май 08, 2024, 22:25 *
Добро пожаловать, Гость. Пожалуйста, войдите или зарегистрируйтесь.
Вам не пришло письмо с кодом активации?

Войти
 
  Начало   Форум  WIKI (Вики)FAQ Помощь Поиск Войти Регистрация  

Страниц: 1 2 [3]   Вниз
  Печать  
Автор Тема: Иерархическая модель  (Прочитано 20812 раз)
kambala
Джедай : наставник для всех
*******
Offline Offline

Сообщений: 4727



Просмотр профиля WWW
« Ответ #30 : Апрель 09, 2016, 23:27 »

в тот же вечер я быстро написал маленький пример и никак не мог понять почему он не работает. начал сравнивать с Simple Tree Model — все было сделано аналогично (только там полноценная модель дерева у них строится, а у меня на if'ах). только что нашел ошибку: в реализации data() у меня отсутствовало игнорирование всех прочих ролей кроме DisplayRole Улыбающийся
ну добавь в Product поле типа Delivery *
это кстати не понадобилось, сохранил указатель в internalPointer()

могу выложить, если еще нужно.
Записан

Изучением C++ вымощена дорога в Qt.

UTF-8 has been around since 1993 and Unicode 2.0 since 1996; if you have created any 8-bit character content since 1996 in anything other than UTF-8, then I hate you. © Matt Gallagher
KlimichKartorgnusov
Гость
« Ответ #31 : Апрель 10, 2016, 09:42 »

в тот же вечер я быстро написал маленький пример и никак не мог понять почему он не работает. начал сравнивать с Simple Tree Model — все было сделано аналогично (только там полноценная модель дерева у них строится, а у меня на if'ах). только что нашел ошибку: в реализации data() у меня отсутствовало игнорирование всех прочих ролей кроме DisplayRole Улыбающийся
ну добавь в Product поле типа Delivery *
это кстати не понадобилось, сохранил указатель в internalPointer()

могу выложить, если еще нужно.

Нужно конечно, выложите пожалуйста.
Записан
kambala
Джедай : наставник для всех
*******
Offline Offline

Сообщений: 4727



Просмотр профиля WWW
« Ответ #32 : Апрель 10, 2016, 12:29 »

структура данных взята упрощенная, но она аналогична ТСовской
Код
C++ (Qt)
#include <QtCore>
#include <QtGui>
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
#include <QtWidgets>
#endif
 
struct Container
{
   QString s;
   QStringList children;
 
   Container(const QString &s_) : s(s_) {}
};
 
class TreeModel : public QAbstractItemModel
{
public:
   TreeModel(QObject *parent = 0) : QAbstractItemModel(parent)
   {
       for (int i = 0; i < 5; ++i)
       {
           Container *c = new Container(QString("root %1").arg(i));
           for (int j = 0; j < 4 - i; ++j)
           {
               c->children << QString("child %1").arg(j);
           }
           list << c;
       }
   }
 
   QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const
   {
       // сохраним указатель на родительский айтем для дальнейшего использования
       return createIndex(row, column, parent.isValid() ? list.at(parent.row()) : 0);
   }
 
   QModelIndex parent(const QModelIndex &child) const
   {
       // родительский индекс есть только у тех, для кого мы сохранили указатель в методе выше
       Container *c = static_cast<Container *>(child.internalPointer());
       return c ? createIndex(list.indexOf(c), 0) : QModelIndex();
   }
 
   int columnCount(const QModelIndex &parent = QModelIndex()) const
   {
       return 1;
   }
 
   int rowCount(const QModelIndex &parent = QModelIndex()) const
   {
       bool hasParent = parent.isValid();
       // без этого условия получится бесконечная вложенность детей
       if (hasParent && parent.internalPointer())
           return 0;
       return hasParent ? list.at(parent.row())->children.size() : list.size();
   }
 
   QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const
   {
       if (role != Qt::DisplayRole)
           return QVariant();
 
       QModelIndex parent = index.parent();
       return parent.isValid() ? list.at(parent.row())->children.at(index.row()) : list.at(index.row())->s;
   }
 
private:
   QList<Container *> list;
};
 
 
int main(int argc, char *argv[])
{
   QApplication a(argc, argv);
 
   QTreeView tv;
   tv.setModel(new TreeModel(&tv));
   tv.show();
 
   return a.exec();
}
 
« Последнее редактирование: Апрель 10, 2016, 12:35 от kambala » Записан

Изучением C++ вымощена дорога в Qt.

UTF-8 has been around since 1993 and Unicode 2.0 since 1996; if you have created any 8-bit character content since 1996 in anything other than UTF-8, then I hate you. © Matt Gallagher
KlimichKartorgnusov
Гость
« Ответ #33 : Апрель 10, 2016, 16:43 »

структура данных взята упрощенная, но она аналогична ТСовской
Код
C++ (Qt)
#include <QtCore>
#include <QtGui>
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
#include <QtWidgets>
#endif
 
struct Container
{
   QString s;
   QStringList children;
 
   Container(const QString &s_) : s(s_) {}
};
 
class TreeModel : public QAbstractItemModel
{
public:
   TreeModel(QObject *parent = 0) : QAbstractItemModel(parent)
   {
       for (int i = 0; i < 5; ++i)
       {
           Container *c = new Container(QString("root %1").arg(i));
           for (int j = 0; j < 4 - i; ++j)
           {
               c->children << QString("child %1").arg(j);
           }
           list << c;
       }
   }
 
   QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const
   {
       // сохраним указатель на родительский айтем для дальнейшего использования
       return createIndex(row, column, parent.isValid() ? list.at(parent.row()) : 0);
   }
 
   QModelIndex parent(const QModelIndex &child) const
   {
       // родительский индекс есть только у тех, для кого мы сохранили указатель в методе выше
       Container *c = static_cast<Container *>(child.internalPointer());
       return c ? createIndex(list.indexOf(c), 0) : QModelIndex();
   }
 
   int columnCount(const QModelIndex &parent = QModelIndex()) const
   {
       return 1;
   }
 
   int rowCount(const QModelIndex &parent = QModelIndex()) const
   {
       bool hasParent = parent.isValid();
       // без этого условия получится бесконечная вложенность детей
       if (hasParent && parent.internalPointer())
           return 0;
       return hasParent ? list.at(parent.row())->children.size() : list.size();
   }
 
   QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const
   {
       if (role != Qt::DisplayRole)
           return QVariant();
 
       QModelIndex parent = index.parent();
       return parent.isValid() ? list.at(parent.row())->children.at(index.row()) : list.at(index.row())->s;
   }
 
private:
   QList<Container *> list;
};
 
 
int main(int argc, char *argv[])
{
   QApplication a(argc, argv);
 
   QTreeView tv;
   tv.setModel(new TreeModel(&tv));
   tv.show();
 
   return a.exec();
}
 

Большое спасибо! Самый человеко понятный пример которой я видел Улыбающийся 
Записан
Страниц: 1 2 [3]   Вверх
  Печать  
 
Перейти в:  


Страница сгенерирована за 0.104 секунд. Запросов: 22.