Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading