QListWidget实现自定义排序,最主要思路为重写QlistWidgetItem类并重载其<运算符;
具体实现如下:
class MyListWidgetItem : public QListWidgetItem
{
public:
bool operator<(const QListWidgetItem &other) const
{
if(0==mType)
{
return QListWidgetItem::operator<(other);
}
else{
long long a, b;
a = this->data(Qt::UserRole + 1).toDouble();
b = other.data(Qt::UserRole + 1).toDouble();
return a < b;
}
}
void setSortType(int t)
{
mType = t;
}
private:
int mType = 0;//0 名称 1 code
};
使用时只需要在addItem时调用一下setSortType()方法将当前排序的规则传入,需要更改时遍历所有Item调用setSortType()更类型,最后使用QListWidget->sortItem()即可实现自定义排序。