Reputation: 71
I am trying to append an object of type student containing a Qlist of QStrings to a Qlist of type students, I have verified that the Qstrings are being added to the student object at one stage, however they seem to be empty when I get to the code below;
for(int i = 0; i < studentList.size(); i++){
qDebug() << studentList.at(i).atindex(i);
Is shown at the bottom.
-Listmanager.h
#ifndef LISTMANAGER_H
#define LISTMANAGER_H
#include <QString>
#include <QList>
#include <QStandardItemModel>
class listManager: QObject
{
Q_OBJECT
public:
listManager();
listManager(QList<QString> list);
QAbstractItemModel* listManager::getmodelview();
QAbstractItemModel* listManager::getclassmodelView();
public:
QStandardItemModel *courseModel = new QStandardItemModel(0,0);
QStandardItemModel *classModel = new QStandardItemModel(0,0);
};
#endif // LISTMANAGER_H
-relevent part of listmanager.cpp
student st;
int count2 = 0;
for (int i =6; i < list.size(); ++i){
if(count2 < 6){
st.appendtolist(list.at(i));
count2++;
}
if(count2 == 6){
count2 =0;
studentList.append(st);
st.showlist();
st.clearlist();
}
}
for(int i = 0; i < studentList.size(); i++){
qDebug() << studentList.at(i).atindex(i);
-student.cpp
#include "student.h"
#include <QDebug>
student::student()
{
}
void student::appendtolist(QString item){
list->append(item);
}
void student::showlist(){
qDebug() << *list;
}
void student::clearlist(){
list->clear();
}
QString student::atindex(int index)const {
for(int i = 0; i < list->size(); i++){
if(index == i){
return list->at(i);
}
}
return "Not Good!";
}
-student.h
#ifndef STUDENT_H
#define STUDENT_H
#include <QString>
#include <QList>
class student
{
public:
QList<QString> *list = new QList<QString>();
student();
void student::appendtolist(QString item);
void student::showlist();
void student::clearlist();
QString atindex(int index) const;
};
#endif // STUDENT_H
Ouput:
"Not Good!" "Not Good!" "Not Good!" "Not Good!" "Not Good!" "Not Good!" "Not Good!" "Not Good!" "Not Good!" "Not Good!" "Not Good!" "Not Good!" "Not Good!" "Not Good!" "Not Good!" "Not Good!" "Not Good!"
Upvotes: 0
Views: 266
Reputation: 49289
It is entirelly pointless and even inefficient to allocate the list dynamically, use QList<QString> list;
instead, change list->
to list.
and *list
to list
You loop for no reason in atindex()
, it is pointless looping through the list until i
hits index
, you can check if index
is in the range of the list with a single expression.
QString student::atindex(int index) const {
if (index < list.size()) return list.at(index); // index is in range
else return "Not good!"; // index is out of range - no good
}
Upvotes: 1