Search code examples
c++qtqt6

How to get reference to item in nested QList


I have an object that contains a QList of objects. Then I have QList of the original object. It basically looks like this:

class study {
    int data;
}

class subject {
    QList <study> studies;
    void AddStudy(study s) { studies.append(s); };
}

QList <subject> subjects;

Building an object and adding it to the top-level QList works fine, like this

study stud;
subject subj;
subj.AddStudy(stud);

But when trying to modify an existing object in the top QList, I only get a copy of the object

subject subj = subjects[i];
study stud;
subj.AddStudy(stud); /* this is only modifying the copy, not the original */

I tried using pointers, but it crashes, I assume because I'm attempting to access an invalid pointer.

I'm wondering how I might achieve this. I think my alternative is to always reference the original top-level QList like subjects[i].studies[i].xyz = ...


Solution

  • subject subj = subjects[i]; creates a copy.

    If you want to call AddStudy on subejcts[i] that is

    subjects[i].AddStudy(stud);
    

    If for whatever reasons you want to do it in two steps you could use a reference:

    auto& sub = subjects[i];
    sub.AddStudy(stud);