Home > Back-end >  Creating an object from database data and appending it to a QList
Creating an object from database data and appending it to a QList

Time:01-28

Why can't I call append on this QList?

QList<Artist> * DataManagement::create_and_get_artists(){

    QList<Artist> *artists = new QList<Artist>;

    for(int i; i < m_allSongs->rowCount(); i  ){
        Artist *artist = new Artist();
        artist->setName(m_allSongs->record(i).value("artistName").toString());
        artists->append(artist);

    }

    return artists;
}

Screenshot of error

Error message: "no matching member function for call to 'append'".

CodePudding user response:

You can call append on a QList type, but only with an appropriate parameter.

In the code, artist is a pointer to the Artist type, while the QList is a list of Artist types.

In the screenshot, no parameter is given at all.

CodePudding user response:

Let's look at the documentation (always check the documentation first!).

There are two overloads of append():

void QList::append(const T &value)

and

void QList::append(const QList<T> &value)

So you can append a value or a list of values.

In your code on the screenshot, you call artists->append();. That is, you are not providing any argument. No member function append() with zero arguments exist.

Managing Object Lifetimes

Remember that you are responsible for managing memory in C ! You have a QList<Artist>, i.e., a list of actual objects. Yet you create an Artist using new. Now you have a pointer to a heap allocated object.

Calling append(obj) will actually copy the object, i.e., call the copy constructor! You are then responsible to free the temporary object you created!

Alternatively, you could use a QList<Artist*>, i.e., a list of pointers. But I think this is the worst option.

You could also construct a temporary object on the stack and then copy it:

Artist artist{};
artist.setName("bla");
artists->append(artist);

But it would be much better - if you use Qt6 - to just construct the object directly into the list, using emplaceBack(). (You need the matching constructor, of course).

  •  Tags:  
  • Related