简体   繁体   English

排序和显示自定义QVariant类型

[英]Sorting and displaying a custom QVariant type

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. 我有一个想与QVariant一起使用的自定义类型,但是我不知道如何使QVariant显示在表中或如何在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. 我使用Q_DECLARE_METATYPE注册该类型,并编写了通过qRegisterMetaTypeStreamOperators注册的流运算符,但是由于某种原因,当我将这种类型与表模型一起使用时,它不会显示任何内容,也不会进行排序。

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. 它具有一个副本和默认构造函数,但我无法修改源代码以使其与QVariant一起使用。 Is there a way of non-intrusively getting the behaviour I'd like? 有没有一种非侵入式获得我想要的行为的方法?

Display : 显示方式

It sounds like your model isn't returning sensible content for the DisplayRole . 听起来您的模型没有为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 . 用于显示模型中所有内容的QAbstractItemDelegate (通常为QStyledItemDelegate )需要了解如何呈现Qt::DisplayRole data()返回的内容。

You have two main options: 您有两个主要选择:

  1. Modify your model so that it returns a sensible Qt::DisplayRole , OR 修改模型,使其返回一个合理的Qt :: DisplayRole ,或者
  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. 如果要编辑该类型的项目,则需要调用registerEditor,以便可以将自定义类型与编辑器相关联。 See the QItemEditorFactory documentation . 请参阅QItemEditorFactory文档

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. 您不能依靠QVariant的比较运算符,因为它不适用于自定义类型,因此您需要实现QSortFilterProxyModel::lessThan才能进行自定义排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM