使用未显示的值(例如 ID)搜索 QTableView
Search QTableView with a value(e.g. ID) which is not displayed
场景:
说,我有一个人class
class Person{
int id; // only unique value, NOT displayed
QString name; // displayed
QString address; // displayed
QString age; // displayed
etc etc // displayed
}
我正在使用的型号class;继承 QAbstractTableModel - MyCustomModelClass : QAbstractTableModel
。 MyCustomModelClass
引用了人员列表。人员列表在名为 MyAllData
的 class 中维护,它在我的模型 class 之外。
table不显示一个人的ID号码。但这是唯一可以单独识别一个人的东西。如果我想用 ID 搜索我的 table 数据,我该怎么做?
这在一定程度上取决于您希望使用哪种方法搜索您的模型 class。通常,我会在您的 data() 方法中实现 Qt::UserRole 。此角色可以 return 只有您的 ID 或指向您完整结构的指针(使用 Q_DECLARE_METATYPE)。
然后,您可以自己处理模型索引,调用
model->data(idx, Qt::UserRole).toValue<Person*>()
或者使用像 QT 的 match(.) 这样的方法并在那里使用 Qt::UserRole。
第三种可能性是 return ID,就好像您想显示它一样,但在您的视图中隐藏该列。
场景:
说,我有一个人class
class Person{
int id; // only unique value, NOT displayed
QString name; // displayed
QString address; // displayed
QString age; // displayed
etc etc // displayed
}
我正在使用的型号class;继承 QAbstractTableModel - MyCustomModelClass : QAbstractTableModel
。 MyCustomModelClass
引用了人员列表。人员列表在名为 MyAllData
的 class 中维护,它在我的模型 class 之外。
table不显示一个人的ID号码。但这是唯一可以单独识别一个人的东西。如果我想用 ID 搜索我的 table 数据,我该怎么做?
这在一定程度上取决于您希望使用哪种方法搜索您的模型 class。通常,我会在您的 data() 方法中实现 Qt::UserRole 。此角色可以 return 只有您的 ID 或指向您完整结构的指针(使用 Q_DECLARE_METATYPE)。
然后,您可以自己处理模型索引,调用
model->data(idx, Qt::UserRole).toValue<Person*>()
或者使用像 QT 的 match(.) 这样的方法并在那里使用 Qt::UserRole。
第三种可能性是 return ID,就好像您想显示它一样,但在您的视图中隐藏该列。