Important: Please read the Qt Code of Conduct -

[solved] Model/view. Best way to add new items to Model and display them in View.

  • Hi guys!

    Continue to study model/view programming in Qt. I have implemented my own model, which is a subclass of QAbstractTableModel. I have my structure GraphData and QList<GraphData> which is container for my data. Also, as I said before I have implemented my own model, which is a wrapper QList<GraphData>(each row in model is my GraphData structure). My problem is that I don't understand yet, how to update Model and View properly, when I add new GraphData to the QList<GraphData>. The only idea which I have now, is to add empty row to the model through insertRows(row,count, index) implementation, then get QModelIndex for each column in this row and through setData(index,value,role) implementation change each value for each QModelIndex. But it seems quite ugly, there should be more convenient way to do that.

  • As far as I understood the Model/View concept you can either implement inserRows() which will add a new "empty" or "default" item or you can do it manually outside of the model by wrapping the line of code that will append to your QList<GraphData> list in beginInsertRows() and endInsertRows().

    Note that you have to use beginInsertRows() and endInsertRows() in the insertRows() implementation as well. I think this is stated in the documentation.

    The purpose of beginInsertRows() is to let all views know that they should not read from the model while the purpose of endInsertRows() is to let the views know that it is time for an update. Hence you don't have to manually update your views at all.

  • Lifetime Qt Champion


    There's no need for outside of the model methods nor reimplementation of insertRows. You should add your custom type handling method to your model subclass e.g. insertGraphData(int rows, const GraphData& data) and do the begin/endInsertRows call in it.

  • @SGaist Tnx, perfect!

Log in to reply