title: Qt Model/View: how to handle underlying data properly
body: <p>I watched tons of videos and spent a lot of time reading papers about models, how to work with them and general idea is quite clear. However, I still don't get several things that really slow me down.</p>
  
  <p>I realize that model works only as an interface between view and data. However, when I look at sample codes, most of the time, some sort of data structure is sent to model and all functions in the model uses that internal model data structure to do required things: evaluate headers, row count etc. Example of such constructor (in this case internal model QList is <code>addressBook</code>):</p>
  
  <pre><code>AddressbookModel::AddressbookModel(const QString&amp; addresses,
    QObject *parent): QAbstractTableModel(parent)
  {
    QStringList records = addresses.split(’\n’);
    QStringList line;
    foreach(QString record, records)
    addressBook.append(splitCSVLine(record));
  }
  </code></pre>
  
  <p>And that looks OK, but it gets very confusing when I try to think about modifying underlying data some where else in the program, when some sort of model is "attached" to that data structure. </p>
  
  <p>For example, lets have a look at this sample code from learning material:</p>
  
  <pre><code>    // addressbook/main.cpp
  #include &lt;QtGui&gt;
  #include "addressbookmodel.h"
  int main( int argc, char* argv[] )
  {
    QApplication app( argc, argv );
    QFile file("addressbook.csv");
    if ( !file.open(QIODevice::ReadOnly|QIODevice::Text) )
      return 1;
    QString addresses = QString::fromUtf8(file.readAll());
    AddressbookModel model(addresses);
    QTableView tableView;
    tableView.setModel(&amp;model);
    tableView.show();
    return app.exec();
  }
  </code></pre>
  
  <p>Here, there is a static variable of <code>addresses</code> which is then sent to <code>model</code>. Now, user would be able to see and modify that data. But what if I want to work more with that data somewhere else in the program? What if I insert new entries to <code>addresses</code>? I realize that model will not see those changes, and in this example (and in many more) that underlying data structure is even sent not as a pointer.</p>
  
  <p>So my question is: how to manage data properly, when I will have new data coming from "behind the scenes" - not only from the model? Should I work with data management only within the model class (implement required functions etc.)? Should I somehow pass only pointers of data to model? Everything gets even more tricky, when I think of using Proxy Models for filtering, because they also work and somewhat "treat" data in their own way. Maybe I missed something important about this architecture, but it really stops me here.</p>