我有QList<m_User>
m_User {
QString status;
QString firstName;
QString lastName;
QDate joinDate;
QDate leaveDate;
}
status
此处可以是:terminated
,in test
,requested
,activated
。
status
的排序顺序应为:activated
- &gt; terminated
- &gt; requested
- &gt; in test
此QList应按此顺序排序:
所以结果看起来应该是
----------------------------------------------------------
| firstName | lastName | status | joinDate | leaveDate |
----------------------------------------------------------
| A | C |activated | bla | bla |
| A | D |activated | bla | bla |
| B | E |activated | bla | bla |
| A | F |terminated| bla | bla |
| A | G |terminated| bla | bla |
| B | H |terminated| bla | bla |
| A | I |requested | bla | bla |
| B | I |requested | bla | bla |
| B | K |requested | bla | bla |
| A | L | in test | bla | bla |
| B | L | in test | bla | bla |
| B | M | in test | bla | bla |
答案 0 :(得分:3)
您可以将lessThen函数添加到您的类/结构中,然后根据需要为qSort创建转发器。 例如:
class m_User {
public:
bool operator<(const m_User other) const {
return a<other.a;
}
};
template <typename T>
struct ForwardLessThen
{
bool operator()(const T* a, const T* b) const
{
return *a < *b;
}
};
qSort(list.begin(), list.end(), ForwardLessThen<m_User>());
如果你使用C ++ 11/14,你可以使用lambdas
QList<const m_User*> l;
qSort(l.begin(), l.end(),
[](const m_User* a, const m_User* b) -> bool { return a->firstName() < b->firstName(); //implement your logic here
});
使用Qt5 qSort实际上已弃用,您应该使用std :: sort函数。
std::sort(container.begin(), container.end(), qLess<T>());
中查看基于模板的算法
编辑:或者,如果您计划使用某种视图模型(如ListView),您甚至可以实现自己的QSortFilterProxyModel
答案 1 :(得分:1)
bool compareUsers(const m_User &u1, const m_User &u2)
{
if(u1.status != u2.status)
{
//compare all possible combination if statuses of the
//u1 user and u2 user and return which has priority
//example activated has priorty over terminated
if(u1.status == "activated" && u2.status =="terminated")
{
return true;
}
else if(u1.status == "terminated" && u2.status =="activated")
{
return false;
}
...
..
.
}
else if(u1.firstName != u2.firstName)
{
return u1.firstName > u2.firstName;
}
else
{
return u1.lastName > u2.lastName;
}
}
然后只需在sort函数中调用谓词
QList<m_User> list;
qSort(list.begin(), list.end(), compareUsers);