2012-12-10 5 views
1

qlistview에 대한 사용자 정의 모델을 구현하려고합니다. 나는 과거 게시물의 링크를 광산과 비슷하게 읽었지만 제대로 작동하지 못했습니다.qabstractlistmodel을 사용하여 사용자 정의 모델로 QListview를 실행할 때

추가 버튼을 클릭하여 사용자가 동적으로 생성해야하는 내 객체를 나열하고 싶습니다. 목록보기에서 항목을 제거하려면 항목을 선택하고 제거 버튼을 클릭해야합니다.

편집 - QAbstractListModel을 상속하는 사용자 지정 모델을 사용하여 qlistview를 만들려고합니다. qlistview에 qlist가 표시되고 모든 항목이 qlistview에 나열되어야합니다. 또한 사용자가 새 MyCustomObject를 만들고 Qlist에 추가하길 원합니다.

Google 검색을 통해 찾을 수있는 게시물과 예제를 따라했지만 지금은 분실했습니다.

추가 버튼을 클릭하면 응용 프로그램이 충돌합니다.

mainwindow.cpp

#include "mainwindow.h" 
#include "ui_mainwindow.h" 

MainWindow::MainWindow(QWidget *parent) : 
    QMainWindow(parent), 
    ui(new Ui::MainWindow) 
{ 
    ui->setupUi(this); 

    QList<MyCustomObject*> *m_list = new QList<MyCustomObject*>; 

    CustomListModel *lmodel = new CustomListModel(this); 

    MyCustomObject *object = new MyCustomObject(this); 

    m_list->append(object); 

    ui->listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); 

    ui->listView->setEditTriggers(QAbstractItemView::NoEditTriggers); 

    lmodel->setmylist(m_list); 

    //Initialize the Listview 
    ui->listView->setModel(lmodel); 
} 

MainWindow::~MainWindow() 
{ 
    delete ui; 
} 

void MainWindow::on_addpushButton_clicked() 
{ 
    MyCustomObject *object = new MyCustomObject(this); 

    lmodel->AddmycustomObject(object); 
} 

void MainWindow::on_removepushButto_clicked() 
{ 

} 

mainwindow.h

#ifndef MAINWINDOW_H 
#define MAINWINDOW_H 

#include <QMainWindow> 
#include <QListView> 
#include <customlistmodel.h> 
#include "mycustomobject.h" 


namespace Ui { 
class MainWindow; 
} 

class MainWindow : public QMainWindow 
{ 
    Q_OBJECT 

public: 
    explicit MainWindow(QWidget *parent = 0); 
    ~MainWindow(); 

private slots: 
    void on_addpushButton_clicked(); 

    void on_removepushButto_clicked(); 

private: 
    Ui::MainWindow *ui; 
    QList<MyCustomObject*> *m_list; 
    CustomListModel *lmodel; 


}; 

#endif // MAINWINDOW_H 

customlistmodel.cpp

#include "customlistmodel.h" 

CustomListModel::CustomListModel(QObject *parent) : 
    QAbstractListModel(parent) 
{ 
} 
QVariant CustomListModel::data(const QModelIndex &index, int role) const 
{ 
    if (!index.isValid()) 
     return QVariant(); 

    if (index.row() >= Model_list->size()) 
     return QVariant(); 

    if (role == Qt::DisplayRole) 
     return QVariant(QString("row [%1]").arg((Model_list->at(index.row()))->GetName())); 
    else 
     return QVariant(); 
} 
int CustomListModel::rowCount(const QModelIndex &parent) const 
{ 
     Q_UNUSED(parent); 
     return Model_list->size(); 
} 
//bool CustomListModel::insertRows(int row, int count, const QModelIndex &parent) 
//{ 
// beginInsertRows(QModelIndex(), row, row+count-1); 


// endInsertRows(); 

// return true; 
//} 


//bool CustomListModel::removeRows(int row, int count, const QModelIndex &parent) 
//{ 
// beginRemoveRows(QModelIndex(), row, row+count-1); 


// endRemoveRows(); 

// return true; 

//} 





//bool CustomListModel::setData(const QModelIndex &index, const QVariant &value, int role) 
//{ 
// if (index.isValid() && role == Qt::EditRole) { 

//  MyCustomObject *item = Model_list->at(index.row()); 
//  item->SetNam(value.toString()); 

//  // Model_list->at(index.row())->SetNam(value.toString()); 
//  emit dataChanged(index,index); 
//  return true; 
// } 
// return false; 

//} 
//Custom Methods 
void CustomListModel::setmylist(QList<MyCustomObject*> *list) 
{ 
    beginResetModel(); 

    Model_list = list; 

    endResetModel(); 
    reset(); 

} 
void CustomListModel::AddmycustomObject(MyCustomObject *object) 
{ 

    int first = Model_list->count(); 
    int last = first; 

      beginInsertRows(QModelIndex(), first, last); 
      Model_list->append(object); 
      endInsertRows(); 

} 

#ifndef CUSTOMLISTMODEL_H 
#define CUSTOMLISTMODEL_H 

#include <QAbstractListModel> 
#include <QList> 
#include "mycustomobject.h" 

class CustomListModel : public QAbstractListModel 
{ 
    Q_OBJECT 
public: 
    explicit CustomListModel(QObject *parent = 0); 
    QVariant data(const QModelIndex &index, int role) const; 
    int rowCount(const QModelIndex &parent) const; 
    // bool setData(const QModelIndex &index, const QVariant &value, int role); 

    // bool insertRows(int row, int count, const QModelIndex &parent); 
    //bool removeRows(int row, int count, const QModelIndex &parent); 

    //Custom Methods 
    void setmylist(QList<MyCustomObject*> *list); 
    void AddmycustomObject(MyCustomObject *object); 
private: 
    QList<MyCustomObject*>* Model_list; 

signals: 

public slots: 

}; 
#endif // CUSTOMLISTMODEL_H 
CustomListModel.h 516,

MyCustomObject.h

#ifndef MYCUSTOMOBJECT_H 
#define MYCUSTOMOBJECT_H 

#include <QObject> 

class MyCustomObject : public QObject 
{ 
    Q_OBJECT 
public: 
    explicit MyCustomObject(QObject *parent = 0); 
    QString Name; 
    QString GetName() {return Name;} 
    void SetNam(QString Value){ Name = Value;} 
signals: 

public slots: 

}; 

#endif // MYCUSTOMOBJECT_H 

mycustomobject.cpp

#include "mycustomobject.h" 

MyCustomObject::MyCustomObject(QObject *parent) : 
    QObject(parent) 
{ 
    this->Name = "TestName"; 
} 

MAIN.CPP

#include <QtGui/QApplication> 
#include "mainwindow.h" 

int main(int argc, char *argv[]) 
{ 
    QApplication a(argc, argv); 
    MainWindow w; 
    w.show(); 

    return a.exec(); 
} 

mainwindow.ui @DanielCastro는이 다루었 enter image description here

+1

을 난 당신이 게시물을 요약하는 것이 좋습니다. 어쨌든, 나는 오타라고 생각하지만 필드를 할당하는 대신 MainWindow 생성자에서 자신의 lmodel 변수를 다시 선언하고 있습니다. 이게 니가 원하는거야? –

+0

동의합니다. 많은 정보를 얻게되어서 고맙지 만, 내가 직면하고있는 실제 문제에 대한 요약 설명을보고 싶습니다. 그런 다음 선택적으로 문제를 파악하고 식별하는 데 필요한 소스 코드를 살펴보십시오. 어떤 부분이 문제를 일으키거나 충돌하거나 예상대로 작동하지 않습니까? – jdi

+0

죄송합니다. 추가 버튼을 클릭하면 응용 프로그램이 중단됩니다. –

답변

3

주요 논평, 그러나 나는 그것이 당신의 실제적인 추락일지도 모른다라고 생각하는 것에 따라 그것을 확대하고있다. 당신의 MainWindow를에서

, 당신은 모델에 대한 개인 회원을 선언

private: 
    ... 
    CustomListModel *lmodel; 

하지만 당신의 MainWindow를 생성자에서

, 당신은 새로운 모델을 초기화하고보기에 그것을 설정 :

MainWindow::MainWindow(QWidget *parent) : 
    QMainWindow(parent), 
    ui(new Ui::MainWindow) 
{ 
    ... 
    // Not actually initializing the private member 
    CustomListModel *lmodel = new CustomListModel(this); 
    ... 

    lmodel->setmylist(m_list); 

    //Initialize the Listview 
    ui->listView->setModel(lmodel); 
} 

그러면 개인 lmodel이 널 포인터로 남습니다.

lmodel = new CustomListModel(this); 
:
void MainWindow::on_addpushButton_clicked() 
{ 
    MyCustomObject *object = new MyCustomObject(this); 
    // CRASH because you access a NULL pointer 
    lmodel->AddmycustomObject(object); 
} 

그래서 수정은 아마 될 것

당신이 MainWindow를 생성자의 개인 회원이 아닌 새로운 모델을 초기화되어 있는지 확인 : 그럼 당신은 그것을 액세스하려고 슬롯이

당신은 너무 또한, 당신의 m_list과 같은 일을하고있다 : 당신이 지금 나 이리저리 선 아래로 잠재적 인 충돌이있을 수 있습니다처럼

m_list = new QList<MyCustomObject*>; 

또한 보인다 m 클래스의 QList 대신 QList 포인터를 사용하십시오. 모델에 완전히 초기화 된 목록 객체가 있는지 확인한 다음 다른 목록에서 설정하거나 지울 수는 있습니다.

private: 
    QList<MyCustomObject*> Model_list; 

그리고 당신은 그들을 좋아 전달할 것 :

void setmylist(QList<MyCustomObject*> &list); 
+0

변경을했지만 응용 프로그램에서 빠져 나온 중단을 호출했습니다. 중단하지 않으면 다음 메시지가 나타납니다. "프로그램이 예기치 않게 끝났습니다. C : \ QTProject \ ListViewWithAbstractListModel \ debug \ ListViewWithAbstractListModel.exe 종료되었습니다. 코드 -1073741819 "를 입력하십시오. –

+1

이제 더 일찍 충돌하고 있습니까? 방금 추가 한 회원 목록을 수정하십시오. 그것은 seg fault인가? 당신은 디버거를 통해 그것을 실행할 수 있고 그것이 충돌하는 곳을 더 잘 이해할 수 있습니까? – jdi

+0

그것은 작동합니다. 고맙습니다! –