1
我剛開始嘗試使用Qt的AbstractListModel,並且作爲一個實踐應用程序,我試圖創建一個模型來存儲自定義對象。類是testperson
,personlistmodel
類和mainwindow
。我的問題是,我的視圖不顯示正確的數據,如果我添加兩個'測試人員的,那麼我的listView顯示兩個空行。那麼有人可以請指導我如何模型的數據格式來查看實際工作?我現在做錯了什麼?QListView顯示空白行? (Qt)
人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);
}
代碼
所以模型存儲無效指針?由於'testPerson'對象在超出範圍時被釋放,所以它顯示空行......對不起,這不符合我的'personlistmodel'函數?? – user1927602 2013-02-19 18:20:07
我不能肯定地說,但這是你的示例代碼做錯了的顯而易見的事情。 – 2013-02-20 09:30:38