QListView显示空行? (QT)

时间:2013-02-19 15:51:09

标签: c++ qt qlistview qabstractlistmodel

我刚刚开始尝试使用Qt的AbstractListModel作为练习应用程序我试图创建一个存储自定义对象的模型。这些类是testpersonpersonlistmodel类和mainwindow。我遇到的问题是我的视图没有显示正确的数据,如果我添加两个'testperson'然后我的listView显示两个空行。那么有人可以指导我如何查看模型的数据格式实际工作???我现在做错了什么?

Person Class.cpp

testPerson::testPerson(const QString &name, QObject *parent):QObject (parent)
{
  this->fName = name;
  connect(this,SIGNAL(pesonAdd()),this,SLOT(personConfirm()));
  emit pesonAdd();
}

void testPerson::setPerson(QString setTo)
{
  fName = setTo;
}

QString testPerson::getPerson() const
{
  return fName;
}


void testPerson::personConfirm()
{
qDebug() << fName << QTime::currentTime().toString();
}

PersonListModel.h

class personListModel : public QAbstractListModel
{
  Q_OBJECT

public:
  explicit personListModel(QObject *parent = 0);
  int rowCount(const QModelIndex &parent = QModelIndex()) const;
  QVariant data(const QModelIndex &index, int role) const;
  bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole);
  Qt::ItemFlags flags(const QModelIndex &index) const;
  //Custom functions
  void addPerson(testPerson &person);
private:
  QList<testPerson*> dataStore;
};

PersonListModel.cpp

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

int personListModel::rowCount(const QModelIndex &parent) const
{
  return dataStore.count();
}

QVariant personListModel::data(const QModelIndex &index, int role) const
{
  if(role != Qt::DisplayRole || role != Qt::EditRole){
    return QVariant();
  }

  if(index.column() == 0 && index.row() < dataStore.count() ){
    return QVariant(dataStore[index.row()]->getPerson());
  }else{
    return QVariant();
  }

}

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

    testPerson *item = dataStore[index.row()];
    item->setPerson(value.toString());

    dataStore.at(index.row())->setPerson(value.toString());
    emit dataChanged(index,index);
    return true;
 }
 return false;
}

Qt::ItemFlags personListModel::flags(const QModelIndex &index) const
{
  if(!index.isValid()){
    return Qt::ItemIsEnabled;
  }
  return Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled;
}

void personListModel::addPerson(testPerson &person)
{
  beginInsertRows(QModelIndex(),dataStore.count(), dataStore.count());
  dataStore.append(&person);
  endInsertRows();
}

在mainWindow.cpp中有一些测试代码

// Inc needed files 

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

  //Test model
  personListModel *model = new personListModel(this);
  testPerson one("Adam Smith",this);
  testPerson two("John Smith",this);
  model->addPerson(one);
  model->addPerson(two);
  ui->listView->setModel(model);
}

1 个答案:

答案 0 :(得分:2)

如果您提供的代码是正确的,那么您在堆栈中声明了testPerson个对象,然后将它们作为指针存储在模型中。令人惊讶的是,这并没有导致崩溃。