qt listwidget排序
时间: 2023-09-19 09:12:37 浏览: 164
在Qt中,可以使用QListWidget来实现列表的展示和排序。QListWidget控件自带升序和降序两种排序规则,按照QListWidgetItem的名字进行字符串排序。可以通过以下代码实现:
```
listwidget->sortItems(Qt::AscendingOrder);//升序
listwidget->sortItems(Qt::DescendingOrder);//降序
```
如果希望不按照字符串排序,而是按照自定义规则排序,可以重写QListWidgetItem类并重载其"<"运算符。如下所示:
```
class listwidgetItem :public QListWidgetItem {
public:
bool operator<(const QListWidgetItem &other) const {
double a, b;
a = this->data(Qt::UserRole).toDouble();
b = other.data(Qt::UserRole).toDouble();
return a < b;
}
};
```
然后,在使用QListWidget添加item时,使用自定义的listwidgetItem类,并设置对应的data值。最后调用`widget->sortItems();`进行自定义排序。完整的代码如下:
```
QListWidget* widget = new QListWidget;
widget->setViewMode(QListView::IconMode);
widget->setStyleSheet("QListWidget::Item{color:black;}");
for (int i = 0; i < 10; i++) {
listwidgetItem* item = new listwidgetItem();
item->setText(QString::number(i));
item->setData(Qt::UserRole, 10-i);
item->setSizeHint(QSize(190, 200));
widget->addItem(item);
}
widget->sortItems();//进行自定义排序
```
这样就可以实现自定义排序的QListWidget。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [QListWidget实现自定义排序](https://blog.csdn.net/weixin_46085162/article/details/123245283)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [QListWidget 自定义排序](https://blog.csdn.net/qq_42444110/article/details/122357825)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文