Skip to content

Instantly share code, notes, and snippets.

@nyanpasu64
Created March 16, 2022 10:47
Show Gist options
  • Save nyanpasu64/61814bafbfdade70b2dbf6d3d9fa6ba8 to your computer and use it in GitHub Desktop.
Save nyanpasu64/61814bafbfdade70b2dbf6d3d9fa6ba8 to your computer and use it in GitHub Desktop.

I've had to spend months figuring QAbstractItemModel out (though I haven't worked with parent-child trees yet). Now you will have the pleasure as well.

Qt's model-view system is a nightmarish abstraction thrusts the horror of the endless complexity on the end user; each model you implement is a subclass and a hundred lines, sometimes more, and KDE apps are composed of models stacked upon models, the inner workings of which are whispered about in hushed tones. Drag-drop is no exception, having three separate ways (to my knowledge) to implement it:

  • QAbstractItemView::startDrag() calls some platform-specific drag-drop code (OLE on Windows). If you perform an internal drop, this platform-specific code calls QListView::dropEvent(), which calls QAIM::moveRow().
  • If it fails, or on non-QListView subclasses, QAbstractItemView::dropEvent() calls QAbstractItemModel::dropMimeData() which either replaces data or calls QAbstractItemModel::decodeData() which calls insertRows(). Once the platform-specific code returns, QAbstractItemView::startDrag() may remove the original items (QAbstractItemViewPrivate::clearOrRemove()). It's necessary to separate insert/remove when dragging items between item views or apps.
  • You can override QAbstractItemModel::dropMimeData() to handle moves (link). This is necessary if you want to implement drag-and-drop internal move in any view other than a QListView, but your underlying data source only allows moves (not insert and delete).

I have notes in a Google Doc (link). For sample code, I have exotracker (link, secondary) and qvgmsplit (link).

In terms of shortcuts when defining item models, I've been recommended https://github.com/OlivierLDff/ObjectListModel/, https://github.com/benlau/qsyncable, and https://github.com/KDAB/KDToolBox/tree/master/qt/model_view/updateableModel. I haven't looked into them though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment