tags:

views:

93

answers:

1

Hello, I have a custom type I'd like to use with QVariant but I don't know how to get the QVariant to display in a table or have it sort in a QSortFilterProxyModel.

I register the type with Q_DECLARE_METATYPE and wrote streaming operators registered via qRegisterMetaTypeStreamOperators but for whatever reason when I use the type with a table model, it doesn't display anything and it doesn't sort.

I should specify that this custom type can not be modified. It has a copy and default constructor, but I can not go in and modify the source code to get it to work with QVariant. Is there a way of non-intrusively getting the behaviour I'd like?

+3  A: 

Display:

It sounds like your model isn't returning sensible content for the DisplayRole. The QAbstractItemDelegate (often a QStyledItemDelegate) that is used to display all content from the model needs to understand how to render the content of returned by data() for the Qt::DisplayRole.

You have two main options:

  1. Modify your model so that it returns a sensible Qt::DisplayRole, OR
  2. Subclass one of the existing delegates and modify it so that it can display your custom variant type correctly.

If you want to edit items of that type, you'll need to call registerEditor so you can associate your custom type to an editor. See the QItemEditorFactory documentation.

Sorting:

You can't rely on the comparison operator for QVariant as it doesn't work with custom types, so you'll need to implement QSortFilterProxyModel::lessThan to have custom sorting.

Kaleb Pederson
Thanks for the reply. The content I return by data() for the DisplayRole is the QVariant containing the custom data structure. Should I be returning something different? Will I need to go into every model that uses this custom type and apply the same logic over and over?That sounds like a lot of work but that may be the only solution.
Kranar
You'll either need to change every model or introduce a delegate on each view that needs to render your custom variant type. You should be able to subclass `QStyledItemDelegate` and implement `displayText` so that it converts your custom variant type to a string for rendering. Then you can call `yourView->setItemDelegate*()` to have it used.
Kaleb Pederson