0

Реализую собственную древовидную модель-представление Qt. Модель наследую как положено от класса QAbstractItemModel. Я поставил 4 столбца в модели, переопределив метод класса QAbstractItemModel

int MusicModel::columnCount(const QModelIndex &parent) const{
    return 4;
}

Метод data переопределил следующим образом:

QVariant MusicModel::data(const QModelIndex &index, int role) const{
//    if (role == Qt::DisplayRole){
        if (index.isValid()){
            int column = index.column();
            Item *item = static_cast<Item *>(index.internalPointer());
            switch (column){
            case 0:
                return item->name();
            case 1:
                if(item->toSong()) return item->toSong()->time();
                break;
            case 2:
                if(item->toSong()) return item->toSong()->rating();
                break;
            case 3:
                qDebug() << QTime::currentTime().toString("HH:mm:ss") << item->name() << column;
                if(item->toSong()) return item->toSong()->name();
                if(item->toArtist()) return item->name();
                break;
            }
        }
        return QVariant();
//    }
}

Пока не акцентирую внимание на ролях, отображаю для всех ролей одинаково. Иерархия выглядит следующим образом:

0 уровень m_root

1 уровень Artist

2 уровнь Album

3 уровень Song

Столкнулся с проблемой, когда пытаюсь отобразить 3 уровень. Он попросту не отображается, если я пытаюсь взаимодействовать с 4-ым столбцом в методе data. Иными словами, если убрать строчку if(item->toSong()) return item->toSong()->name(); или добавить 5-ый столбец (columnCount вернёт 5). Только тогда 3-ий уровень вложенности сможет открыться в представлении. Сейчас же ситуация выглядит так:введите сюда описание изображения

Как вы можете заметить, Есть 2 артиста: "ИМЯ" и "Second_a". Также есть 4 альбома у первого артиста ("m2", "m3", "m4", "4-ый"). Но у меня не получается раскрыть альбом "m2", чтобы увидеть вложенные песни. Таким образом, не удаётся отредактировать последний столбец модели... Возниакет вопрос: Почему на последнем уровне вложенности у меня не получается редактировать последний элемент?

Ниже прикладываю код проекта. Заранее спасибо за помощь!

musicmodel.h:

#ifndef MUSICMODEL_H
#define MUSICMODEL_H
#include <QAbstractItemModel>
#include <item.h>

class MusicModel : public QAbstractItemModel
{
    Item *m_root;
public:
    MusicModel();
    MusicModel(Item *_m_root){ m_root = _m_root;};
    QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
    QModelIndex parent(const QModelIndex &index) const;
    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent) const;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    Qt::ItemFlags flags(const QModelIndex &index) const;
    bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole);
    bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex());
    bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex());
};

#endif // MUSICMODEL_H

musicmodel.cpp:

#include "musicmodel.h"
#include <QDebug>

MusicModel::MusicModel()
{
    m_root = new Item;
}

QModelIndex MusicModel::index(int row,int column,const QModelIndex &parent) const
{
    Item *parentItem = m_root;

    if(parent.isValid())
        parentItem = static_cast<Item*>(parent.internalPointer());
    if (parentItem->childAt(row))
        return createIndex(row, column, parentItem->childAt(row));

    return QModelIndex();
}

QModelIndex MusicModel::parent(const QModelIndex &index) const{
    if (!index.isValid())return QModelIndex();
    Item *childItem = static_cast<Item *>(index.internalPointer());
    Item *parent = childItem->parent();
    if ((parent == m_root) || !(parent)) return QModelIndex();
    Item *grandparent = parent->parent();
    return createIndex(grandparent->indexOf(parent), 0, parent);
}

int MusicModel::rowCount(const QModelIndex &parent) const{
    Item *parentItem = m_root;
    if(parent.isValid())
        parentItem = static_cast<Item *>(parent.internalPointer());
    return parentItem->childCount();
}

int MusicModel::columnCount(const QModelIndex &parent) const{
    return 4;
}

QVariant MusicModel::data(const QModelIndex &index, int role) const{
//    if (role == Qt::DisplayRole){
        if (index.isValid()){
            int column = index.column();
            Item *item = static_cast<Item *>(index.internalPointer());
            switch (column){
            case 0:
                return item->name();
            case 1:
                if(item->toSong()) return item->toSong()->time();
                break;
            case 2:
                if(item->toSong()) return item->toSong()->rating();
                break;
            case 3:
                qDebug() << QTime::currentTime().toString("HH:mm:ss") << item->name() << column;
                if(item->toSong()) return item->toSong()->name();
                if(item->toArtist()) return item->name();
                break;
            }
        }
        return QVariant();
//    }
//    else if(role == Qt::EditRole){

//    }
}

Qt::ItemFlags MusicModel::flags(const QModelIndex &index) const{
    return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
}

bool MusicModel::setData(const QModelIndex &index, const QVariant &value, int role){

}

bool MusicModel::insertRows(int row, int count, const QModelIndex &parent){

}

bool MusicModel::removeRows(int row, int count, const QModelIndex &parent){

}

Item.h:

#ifndef ITEM_H
#define ITEM_H
#include <QList>
#include <QPixmap>
#include <QTime>
#include <QDataStream>

class Artist;
class Album;
class Song;

class Item {
public:
    Item();
    Item(const QString &);
    ~Item();
    Item *parent() const;
    void setParent(Item *);
    void insertChild(Item *, int position = -1);
    Item *takeChild(int);
    Item *childAt(int) const;
    int indexOf(Item*) const;
    int childCount() const;
    QString name() const{ return m_name; }
    void setName(const QString & _name){ m_name = _name; }
    virtual Artist *toArtist() { return 0; }
    virtual Album *toAlbum() { return 0; }
    virtual Song *toSong() { return 0; }
private:
    Item *m_parent;
    QList<Item*> m_children;
    QString m_name;
    QString m_comment;
};

class Artist : public Item{
    QPixmap _picture;
    QString _country;
    QString _comment;
public:
    Artist() : Item() {}
    Artist(const QString &n) : Item(n) {}
    const QPixmap picture() const{ return _picture; }
    void setPicture(const QPixmap &_p) { _picture = _p; }
    const QString country() const{ return _country; }
    void setCountry(const QString &_c) { _country = _c; }
    const QString comment() const{ return _comment; }
    void setComment(const QString &_c) { _comment = _c; }
    Artist *toArtist() { return this; }
    Album *toAlbum() { return 0; }
    Song *toSong() { return 0; }
};

class Album : public Item{
    int _year;
    QPixmap _picture;
    QString _genre;
    QString _comment;
public:
    Album() : Item() {}
    Album(const QString &n) : Item(n) {}
    int year() const{ return _year; }
    void setYear(int _y) { _year = _y; }
    const QPixmap picture() const{ return _picture; }
    void setPicture(const QPixmap &_p) { _picture = _p; }
    const QString genre() const{ return _genre; }
    void setGenre(const QString &_g) { _genre = _g; }
    const QString comment() const{ return _comment; }
    void setComment(const QString &_c) { _comment = _c; }
    Artist *toArtist() { return 0; }
    Album *toAlbum() { return this; }
    Song *toSong() { return 0; }
};

class Song : public Item{
    QTime _time;
    int _rating;
    QString _comment;
public:
    Song() : Item() {}
    Song(const QString &n) : Item(n) {}
    const QTime time() const{ return _time; }
    void setTime(const QTime &_t) { _time = _t; }
    int rating() const{ return _rating; }
    void setRating(int _r) { _rating = _r; }
    QString comment() const{ return _comment; }
    void setComment(const QString &_c) { _comment = _c; }
    Artist *toArtist() { return 0; }
    Album *toAlbum() { return 0; }
    Song *toSong() { return this; }
};

QDataStream& operator<<(QDataStream &, const Artist &);
QDataStream& operator<<(QDataStream &, const Album &);
QDataStream& operator<<(QDataStream &, const Song &);
QDataStream& operator>>(QDataStream &, Artist &);
QDataStream& operator>>(QDataStream &, Album &);
QDataStream& operator>>(QDataStream &, Song &);
#endif // ITEM_H

Item.cpp:

#include "item.h"
#include <QDebug>


Item::Item(){
    m_parent = 0;
    m_name = "Безымянный";
}

Item::Item(const QString &name){
    m_parent = 0;
    m_name = name;
}

Item::~Item(){
    qDebug() << "delete" << name();
    int count = childCount();
    if (m_parent)m_parent->m_children.takeAt(m_parent->indexOf(this));
    for (int i = 0; i < count; i++) delete childAt(0);
}

void Item::insertChild(Item *child, int position){
    if(position < 0)position = childCount();
    if (!m_children.contains(child))m_children.insert(position, child);
    if (child->parent() != this)child->setParent(this);
}

Item *Item::takeChild(int position){
    Item *child = m_children.takeAt(position);
    child->setParent(0);
    return child;
}

void Item::setParent(Item *_parent){
    if (_parent){
        if (m_parent){
            m_parent->takeChild(m_parent->indexOf(this));
        }
        m_parent = _parent;
        m_parent->insertChild(this);
    }
    m_parent = _parent;
}

Item *Item::parent() const{
    return m_parent;
}


Item *Item::childAt(int position) const{
    if (position < 0 || position >= childCount()) return nullptr;
    return m_children.at(position);
}

int Item::indexOf(Item* el) const{
    return m_children.indexOf(el);
}

int Item::childCount() const{
    return m_children.size();
}

QDataStream& operator<<(QDataStream &stream, const Artist &artist) {

    stream << artist.name() << artist.picture() << artist.country()
           << artist.comment();
    // serialize children
    int cnt = artist.childCount();
    stream << cnt;
    for(int i=0; i<cnt; ++i){
        Album *album = artist.childAt(i)->toAlbum();
        if(album) stream << *album;
    }
    return stream;
}

QDataStream& operator<<(QDataStream &stream, const Album &album){

    stream << album.name() << album.year() << album.picture()
           << album.genre() << album.comment();
    int cnt = album.childCount();
    stream << cnt;
    for (int i = 0; i < cnt; i++){
        Song *song = album.childAt(i)->toSong();
        if (song) stream << *song;
    }
    return stream;
}

QDataStream& operator<<(QDataStream &stream, const Song &song){

    stream << song.name() << song.time() << song.rating()
           << song.comment();
    return stream;
}

QDataStream& operator>>(QDataStream &stream, Artist &artist){
    QString name;
    QPixmap picture;
    QString country;
    QString comment;
    stream >> name >> picture >> country >> comment;
    artist.setName(name);
    artist.setPicture(picture);
    artist.setCountry(country);
    artist.setComment(comment);
    int cnt;
    stream >> cnt;
    Album *album;
    for (int i = 0; i < cnt; i++){
        album = new Album;
        stream >> *album;
        artist.insertChild(album);
    }
    return stream;
}

QDataStream& operator>>(QDataStream &stream, Album &album){
    QString name;
    int year;
    QPixmap picture;
    QString genre;
    QString comment;
    stream >> name >> year >> picture >> genre >> comment;
    album.setName(name);
    album.setYear(year);
    album.setPicture(picture);
    album.setGenre(genre);
    album.setComment(comment);
    int cnt;
    stream >> cnt;
    Song *song;
    for (int i = 0; i < cnt; i++){
        song = new Song;
        stream >> *song;
        album.insertChild(song);
    }
    return stream;
}

QDataStream& operator>>(QDataStream &stream, Song &song){
    QString name;
    QTime time;
    int rating;
    QString comment;
    stream >> name >> time >> rating >> comment;
    song.setName(name);
    song.setTime(time);
    song.setRating(rating);
    song.setComment(comment);
    return stream;
}

main.cpp:

#include "mainwindow.h"
#include <QList>
#include <QApplication>
#include <QDebug>
#include <item.h>
#include <QDataStream>
#include <QFileDialog>
#include <QTreeView>
#include <musicmodel.h>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
//    MainWindow w;
//    w.show();
//    QList<int> l;
//    l.append(1);
//    l.append(2);
//    l.insert(-10, 0);
//    qDebug() << l.takeAt(0);
//    qDebug() << l.takeAt(0);
//    qDebug() << l.indexOf(1);
    Item *_m1 = new Artist;
    Artist *m1 = _m1->toArtist();
    m1->setComment("comment0");
    m1->setCountry("RUSSIA");
    m1->setPicture(QPixmap());
    m1->setName("ИМЯ");
    Item *_m2 = new Album("m2");
    Album *m2 = _m2->toAlbum();
    m2->setComment("comment1");
    m2->setYear(1993);
    m2->setGenre("ROCK");
//    QString name = QFileDialog::getOpenFileName(0, "Open", QDir::currentPath());
//    qDebug() << name;
//    m2->setPicture(QPixmap(name));
    m2->setPicture(QPixmap("C:/Users/Public/Pictures/Sample Pictures/Chrysanthemum.jpg"));
    Album *m3 = new Album("m3");
    Album *m4 = new Album("m4");
    Item *_m5 = new Song("m5");
    Song *m5 = _m5->toSong();
    m5->setTime(QTime());
    m5->setRating(4);
    m5->setComment("comment2");
    Song *m6 = new Song("m6");
    m1->insertChild(m2);
//    m1->insertChild(m4);
    m4->setParent(m1);
    m2->insertChild(m5);
    m4->insertChild(m6);
    m1->insertChild(m3, 1);
//    m6->setParent(m3);
    qDebug() << m1->childCount();
//    qDebug() << m1->childAt(1)->name();
//    delete m4;
//    qDebug() << m3->parent() << m3 << m3->childCount() << m3->name();
//    Item *cur;
//    qDebug() << m1->childAt(0)->name();
//    cur = m1->takeChild(0);
//    qDebug() << cur->name() << cur->parent() << "cur";
//    qDebug() << m1->indexOf(m4) << "index";
    qDebug() << m1->childAt(0)->name() << m1->childAt(0)->toAlbum() << m1->comment() << m1->country() << m1->picture();
    qDebug() << m2->year() << m2->comment() << m2->picture() << m2->genre();
    qDebug() << m1->parent() << m1 << m1->childCount() << m1->name();
    qDebug() << m2->parent()->name() << m2 << m2->childCount() << m2->name();
    qDebug() << m3->parent()->name() << m3 << m3->childCount() << m3->name();
    qDebug() << m4->parent()->name() << m4 << m4->childCount() << m4->name();
    qDebug() << m5->parent()->name() << m5 << m5->childCount() << m5->name()
             << m5->time() << m5->rating() << m5->comment();
    qDebug() << (m5 == nullptr);
    qDebug() << m6->parent()->name() << m6 << m6->childCount() << m6->name();
    qDebug() << m1->childAt(1)->name();
    QFile file("D:/Qt/Code/Music/new.txt");
    QDataStream stream(&file);
    if (file.open(QIODevice::WriteOnly)){
        stream << *m1;
    }
    file.close();
    Artist *artist = new Artist;
    if (file.open(QIODevice::ReadOnly)){
        stream >> *artist;
    }
    qDebug() << "Deserialization";
    qDebug() << artist->childCount();
    qDebug() << artist->childAt(0)->name() << artist->childAt(0)->toAlbum()
             << artist->comment() << artist->country() << artist->picture();
    Album *album_1;
    album_1 = artist->childAt(0)->toAlbum();
    qDebug() << album_1->year() << album_1->comment()
             << album_1->picture() << album_1->genre();
    qDebug() << artist->parent() << artist << artist->childCount() << artist->name();
    qDebug() << album_1->parent()->name() << album_1
             << album_1->childCount() << album_1->name();
    Album *album_2;
    album_2 = artist->childAt(1)->toAlbum();
    qDebug() << album_2->parent()->name() << album_2
             << album_2->childCount() << album_2->name();
    Album *album_3;
    album_3 = artist->childAt(2)->toAlbum();
    qDebug() << album_3->parent()->name() << album_3
             << album_3->childCount() << album_3->name();
    Song *song_1, *song_2;
    song_1 = album_1->childAt(0)->toSong();
    qDebug() << song_1->parent()->name() << song_1 << song_1->childCount()
             << song_1->name() << song_1->time() << song_1->rating()
             << song_1->comment();
    qDebug() << (song_1 == nullptr);
    song_2 = album_3->childAt(0)->toSong();
    qDebug() << song_2->parent()->name() << song_2
             << song_2->childCount() << song_2->name();
    qDebug() << artist->childAt(1)->name();

    Item *root = new Item;
    root->insertChild(artist);
    Artist *artist2 = new Artist;
    artist2->setName("Second_a");
    artist2->setParent(root);
    MusicModel *model = new MusicModel(root);
    QModelIndex index_a1 = model->index(0,0,QModelIndex());
    QModelIndex index_a2 = model->index(1,0,QModelIndex());
    Album *album4 = new Album("4-ый");
    artist->insertChild(album4);
    qDebug() << "Артист 1" << static_cast<Item*>((index_a1).internalPointer())->name()
             << "Родитель" << static_cast<Item*>((model->parent(index_a1)).internalPointer())
             << "Строк" << model->rowCount(index_a1) << "Колонок" << model->columnCount(index_a1);
    qDebug() << "Артист 2" << static_cast<Item*>((index_a2).internalPointer())->name()
             << "Строк" << model->rowCount(index_a2) << "Колонок" << model->columnCount(index_a2);
    QModelIndex index_a_1_1 = model->index(0, 0, index_a1);
    qDebug() << "Альбом 1" << static_cast<Item*>((index_a_1_1).internalPointer())->name()
             << "Родитель" << static_cast<Item*>((model->parent(index_a_1_1)).internalPointer())->name()
             << "Строк" << model->rowCount(index_a_1_1) << "Колонок" << model->columnCount(index_a_1_1);
    QModelIndex index_a_1_2 = model->index(1, 0, index_a1);
    qDebug() << "Альбом 2" << static_cast<Item*>((index_a_1_2).internalPointer())->name()
             << "Строк" << model->rowCount(index_a_1_2) << "Колонок" << model->columnCount(index_a_1_2);
    QModelIndex index_a_1_3 = model->index(2, 0, index_a1);
    qDebug() << "Альбом 3" << static_cast<Item*>((index_a_1_3).internalPointer())->name()
             << "Строк" << model->rowCount(index_a_1_3) << "Колонок" << model->columnCount(index_a_1_3);
    QModelIndex index_a_2_1 = model->index(0, 0, index_a_1_1);
    qDebug() << "Песня 1" << static_cast<Item*>((index_a_2_1).internalPointer())->name()
             << "Родитель" << static_cast<Item*>((model->parent(index_a_2_1)).internalPointer())->name()
             << "Строк" << model->rowCount(index_a_2_1) << "Колонок" << model->columnCount(index_a_2_1);
    QTreeView *tree = new QTreeView;
    tree->setModel(model);
    tree->show();
    /*
    QFile file("D:/Qt/Code/Music/new.txt");
    QDataStream stream(&file);
    if (file.open(QIODevice::WriteOnly | QIODevice::Append)){
        stream << QString("ads") << 123 << QString("last");
        if (stream.status() != QDataStream::Ok){
            qDebug() << "Ошибка записи.";
        }
    }
    file.close();
    QString first, last, another;
    int middle;
    if (file.open(QIODevice::ReadOnly)){
        stream >> first >> middle >> last >> another;
//        stream >> middle;
//        stream >> last;
//        stream >> another;
    }
    qDebug() << first << middle << last << another;
    file.close();
    */
    return a.exec();
}
1
  • 1
    Закиньте проект на какой-нибудь git репозитарий. в таком виде врядли кто-то захочет ковыряться 21 янв 2020 в 3:32

1 ответ 1

0

Всё оказалось довольно простым. Нужно было оставить лишь роль Qt::DisplayRole и возможно Qt::EditRole в функции data. Это решает мою проблему с невозможностью развернуть дерево на всех уровнях.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.