Passing QList reference dont reflect changes like spected



  • Hi, learning about Model/View, create a simple program that take
    tablemodel.cpp and tablemodel.h from the sample
    http://qt-project.org/doc/qt-4.8/itemviews-addressbook.html

    I my dialog only have a button and a QTableView.
    the button run the next code:
    @ void dlgViewer::insertBtnClick()
    {
    qDebug()<< "Insert " ;
    // pairlist is defined in header like
    // QList<QPair<QString, QString> > pairlist ;

     QPair<QString, QString> pair("name0", "address0");
     QPair<QString, QString> pair1("name1", "address1");
     QPair<QString, QString> pair2("name2", "address2");
     pairlist.append(pair);
     pairlist.append(pair1);
     pairlist.append(pair2);
    
     contentTableModel->setList(pairlist);
     //until here the contentTableView show the added pairs
     // the next changes not are reflected
    
      QPair<QString, QString> pair3("name3", "address3");
    
    
    
     pairlist.append(pair3);
     pairlist.append(pair3);
    
     contentTableModel->layoutChanged();
    
     qDebug()<<"pairlist count: "<< pairlist.count();// print 5
    
     qDebug()<<"model content count: "<< contentTableModel->contentCount();//print 3
    

    }
    @

    The problem is that the changes in the original list not are reflected in the model list.
    Debug output is:
    @
    Insert
    model count befor: 0
    model count after: 3
    pairlist count: 5
    model content count: 3
    @

    In the contentTableView only see 3 pairs

    In the TableModel.cpp added a method that pass the reference to the list:

    @void TableModel::setList(QList<QPair<QString, QString> > & alistofPairs)

    {
    qDebug()<<"model count befor: " << listOfPairs.count();
    listOfPairs= alistofPairs;
    qDebug()<< "model count after: " << listOfPairs.count();
    emit (layoutChanged());

    }@
    Also Qlist is Implicit Sharing that mean a shallow copy.

    I dont want to store my data in the model, only want to send the reference to my data
    What is wrong,


  • Lifetime Qt Champion

    Hi,

    Shallow copy indeed but also means copy on write. Since you are modifying your list after setting in on your model you will have a new list.



  • Sorry for my English capabilities reading the implicit sharing document dont understand the "copy-on-write"
    Wich would be the correct way to passing an avoid copy.
    Must to use a pointer ?
    Can give me a little code sample.

    Greetings


  • Lifetime Qt Champion

    It means that when you write something in one of the shallow copies, it will at that moment do the deep copy for that variable.

    Yes in that case you can use a pointer


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.