0

I followed the Qt guidelines for implementing a custom QAbstractTableModel; that is, I implemented the virtual function insertRows. The declaration of this function does not take any custom data structures. Thus the function simply uses the default constructor to create my data structure.

What if I have an existing custom object that I want to insert? Since I see no way of inserting an already existing object in insertRows (due to its function signature), I feel forced to implement a default constructor, call insertRows to insert an empty object, and then call setData to replace the empty object with the already existing object.

Am I doing this wrong? Is there a better way?

It's Your App LLC
  • 4,397
  • 4
  • 34
  • 81

1 Answers1

1
  • If your data items are implemented using the pimpl idiom, default construction can be a trivial operation - you simply set the d-pointer to zero.

  • If you were to use QVariant for internal storage, you can default-construct a null variant instead of default-constructing your object.

You're completely free to implement additional methods for your model that make it easier for you to use. The Qt-bundled views of course won't use such methods. This isn't much of a problem for insertion, since none of the Qt-provided views insert data by themselves. There's literally no code in those views does any data insertion. The data insertion has to be implemented separately, and the data is inserted directly into the model. The view gets notified of such changes, of course. You need to handle the insertRows if you intend your model to interoperate with code not under your control, or if you wish to avoid surprises to others in a team project.

A couple of views come with Qt, some of them derive from QAbstractItemView. Nothing forces you to implement your view as a subclass of QAbstractItemView, mind you. Qt even provides one such view adapter - QDataWidgetMapper. It acts like a view, but doesn't derive from QAbstractItemView.

Community
  • 1
  • 1
Kuba hasn't forgotten Monica
  • 88,505
  • 13
  • 129
  • 275