2017-04-19 8 views
0

Qt example forQAbstractItemModel을 사용하고 에 Item을 추가하려고합니다. QML QAbstractItemModel : 인덱스 i에 삽입하는 방법

내가 문서를 읽고 내가 this

을 사용하려고하지만 예상 대신 new Item을 추가하는대로 작동하지 않는, 그냥 이미 존재하는 항목를 복사합니다.

내가 원하는 무엇 : 여기

는 예를 들어 당신이 버튼을 클릭하면 것이다 인덱스 2 ' 사자'라는 새로운 동물에서 삽입. 그러나 그 대신에 기존 동물을 삽입합니다. 기능은 test()입니다.

#include <QAbstractListModel> 
#include <QStringList> 
#include <qqmlcontext.h> 
//![0] 
class Animal 
{ 
public: 
    Animal(const QString &type, const QString &size); 
//![0] 

    QString type() const; 
    QString size() const; 

private: 
    QString m_type; 
    QString m_size; 
//![1] 
}; 

class AnimalModel : public QAbstractListModel 
{ 
    Q_OBJECT 
public: 

    Q_INVOKABLE void test() ; 
    void setName(const QString &name); 
    enum AnimalRoles { 
     TypeRole = Qt::UserRole + 1, 
     SizeRole 
    }; 

    AnimalModel(QObject *parent = 0); 
//![1] 
//! 
//! 
    void setContext(QQmlContext *ctx) { 
     m_ctx = ctx; 
    } 

    void addAnimal(const Animal &animal); 

    int rowCount(const QModelIndex & parent = QModelIndex()) const; 

    QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const; 
    QHash<int, QByteArray> roleNames() const; 

protected: 

private: 
    QList<Animal> m_animals; 
    QQmlContext* m_ctx; 

signals: 
    void dataChanged(const QModelIndex & topLeft, const QModelIndex & bottomRight); 
//![2] 
}; 
//![2] 

model.h

#include "model.h" 
#include "qDebug" 
Animal::Animal(const QString &type, const QString &size) 
    : m_type(type), m_size(size) 
{ 
} 

QString Animal::type() const 
{ 
    return m_type; 
} 

QString Animal::size() const 
{ 
    return m_size; 
} 




AnimalModel::AnimalModel(QObject *parent) 
    : QAbstractListModel(parent) 
{ 
} 

void AnimalModel::addAnimal(const Animal &animal) 
{ 
    beginInsertRows(QModelIndex(), rowCount(), rowCount()); 
    m_animals << animal; 
    endInsertRows(); 
} 

void AnimalModel::test() { 

    beginInsertRows(QModelIndex(), 2, 2); 
    m_animals.append(Animal("Lion", "Large")); 
    endInsertRows(); 

} 

int AnimalModel::rowCount(const QModelIndex & parent) const { 
    Q_UNUSED(parent); 
    return m_animals.count(); 
} 

QVariant AnimalModel::data(const QModelIndex & index, int role) const { 
    if (index.row() < 0 || index.row() >= m_animals.count()) 
     return QVariant(); 

    const Animal &animal = m_animals[index.row()]; 
    if (role == TypeRole) 
     return animal.type(); 
    else if (role == SizeRole) 
     return animal.size(); 
    return QVariant(); 
} 

//![0] 
QHash<int, QByteArray> AnimalModel::roleNames() const { 
    QHash<int, QByteArray> roles; 
    roles[TypeRole] = "type"; 
    roles[SizeRole] = "size"; 
    return roles; 
} 
//![0] 

model.cpp

#include "model.h" 

#include <QGuiApplication> 
#include <qqmlengine.h> 
#include <qqmlcontext.h> 
#include <qqml.h> 
#include <QtQuick/qquickitem.h> 
#include <QtQuick/qquickview.h> 

//![0] 
int main(int argc, char ** argv) 
{ 
    QGuiApplication app(argc, argv); 

    AnimalModel model; 
    model.addAnimal(Animal("Wolf", "Medium")); 
    model.addAnimal(Animal("Polar bear", "Large")); 
    model.addAnimal(Animal("Quoll", "Small")); 

    QQuickView view; 
    view.setResizeMode(QQuickView::SizeRootObjectToView); 
    QQmlContext *ctxt = view.rootContext(); 
    ctxt->setContextProperty("myModel", &model); 
//![0] 

    view.setSource(QUrl("qrc:view.qml")); 


    view.show(); 

    return app.exec(); 
} 

MAIN.CPP

import QtQuick 2.0 
import QtQuick 2.4 
import QtQuick.Controls 1.3 
import QtQuick.Window 2.2 
import QtQuick.Dialogs 1.2 
import QtQuick.Layouts 1.2 
import QtQml.Models 2.1 
import QtQuick.Controls.Styles 1.2 


//![0] 
ListView { 
    width: 200; height: 250 

    model: myModel 
    delegate: Text { text: "Animal: " + type + ", " + size } 

    MouseArea { 
     anchors.fill: parent 
     cursorShape: Qt.PointingHandCursor 
     onClicked: { 

     } 
    } 
    Button { 
     anchors.bottom: parent.bottom 
     width:50; height:50 
     text:"click" 
     onClicked: { 
      myModel.test() 
     } 

    } 

} 
//![0] 

View.qml

왜 작동하지 않는가? 감사합니다.

답변

1

나는 문제가 실제로 모델에 데이터를 추가 한 라인 가정

m_animals.append(Animal("Lion", "Large")); 

당신은 단지 그것이 적절한 인덱스를 삽입하는 대신 QList<Animal> m_animals;에 추가!?

m_animals.insert(2, Animal("Lion", "Large")); 

따라서 모델 데이터는 본질적으로 손상되고 데이터는 복사되지 않지만 잘못된 위치에 삽입됩니다.

+0

좋아, 모델의 데이터 순서가보기에 문제가되지 않는다고 생각했습니다. 답변 해 주셔서 감사합니다. –

+0

왜'm_animals.insert (2, Animal ("Lion", "Large"));가 맞지 않습니까? http://doc.qt.io/qt-5/qlist.html#insert 물론 순서가 중요합니다. 뷰는 단지'QList' 모델을 표시하고, 뷰 인덱스 2가 변경되었다고 말하면 업데이트 만합니다. 그 색인은 아니고 전체 목록이 아니므로 색인 2의 값이 전혀 변경되지 않았기 때문에 데이터가 뷰에 복사되는 것처럼 보입니다. – xander

+0

나는 나의 대답을 편집했다, 너 괜찮 았어! :) 다시 한번 감사드립니다. –

관련 문제