pyqt5 qtreewidget 文本 排序
时间: 2023-08-30 15:11:02 浏览: 169
PyQt——QTreeWidget限制拖拽区域
可以使用`QSortFilterProxyModel`来对`QTreeWidget`中的文本进行排序。具体步骤如下:
1. 创建`QSortFilterProxyModel`对象,并将其设置为`QTreeWidget`的模型。
```
proxy_model = QSortFilterProxyModel()
proxy_model.setSourceModel(tree_widget.model())
tree_widget.setModel(proxy_model)
```
2. 设置`QSortFilterProxyModel`的排序规则,这里以按照第一列的文本进行升序排序为例。
```
proxy_model.setSortRole(Qt.DisplayRole) # 按照显示文本排序
proxy_model.setSortCaseSensitivity(Qt.CaseInsensitive) # 忽略大小写
proxy_model.sort(0, Qt.AscendingOrder) # 按照第一列升序排序
```
完整代码示例:
```python
from PyQt5.QtWidgets import QApplication, QTreeWidgetItem, QTreeView, QSortFilterProxyModel
from PyQt5.QtCore import Qt
app = QApplication([])
tree_widget = QTreeView()
tree_widget.setHeaderLabels(['Name', 'Age', 'Gender'])
root = QTreeWidgetItem(tree_widget, ['Tom', '25', 'Male'])
QTreeWidgetItem(root, ['Alice', '22', 'Female'])
QTreeWidgetItem(root, ['Bob', '28', 'Male'])
QTreeWidgetItem(root, ['Cathy', '30', 'Female'])
proxy_model = QSortFilterProxyModel()
proxy_model.setSourceModel(tree_widget.model())
tree_widget.setModel(proxy_model)
proxy_model.setSortRole(Qt.DisplayRole)
proxy_model.setSortCaseSensitivity(Qt.CaseInsensitive)
proxy_model.sort(0, Qt.AscendingOrder)
tree_widget.show()
app.exec_()
```
阅读全文