python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > PyQt5 QItemSelection

PyQt5 QItemSelection类使用小结

作者:wanglaqqqq

本文主要介绍了PyQt5 QItemSelection类使用小结,它通过存储多个 QItemSelectionRange 对象来记录复杂的选择区域,支持跨行、跨列或任意单元格组合的选择,感兴趣的可以了解一下

QItemSelection 是 PyQt5 模型/视图框架中用于管理 ​多个项目选择范围的类,常用于处理用户在多选操作(如表格、列表的多选)中的选中状态。它通过存储多个 QItemSelectionRange 对象来记录复杂的选择区域,支持跨行、跨列或任意单元格组合的选择。

核心功能

常用方法

方法说明返回值
append(range: QItemSelectionRange)添加一个选择范围到当前选中区域None
merge(other: QItemSelection)合并另一个 QItemSelection 到当前实例None
split(range: QItemSelectionRange)将指定范围拆分成更小的范围QItemSelection
contains(index: QModelIndex)判断某个索引是否在选中范围内bool
count()返回选中范围的数量int
clear()清空所有选择范围None

​关键代码示例

​1. 创建并操作选择范围

from PyQt5.QtCore import QItemSelection, QItemSelectionRange, QModelIndex

# 假设存在模型索引 index1 和 index2(如表格中的单元格)
index1 = QModelIndex()  # 实际使用时需从模型获取有效索引
index2 = QModelIndex()  # 例如: model.index(0, 0), model.index(2, 2)

# 创建选择范围(从 index1 到 index2 的矩形区域)
range1 = QItemSelectionRange(index1, index2)

# 初始化 QItemSelection 并添加范围
selection = QItemSelection()
selection.append(range1)

# 检查索引是否被选中
print("是否包含 index1:", selection.contains(index1))  # True

​2. 合并两个选择区域

# 创建另一个选择范围
range2 = QItemSelectionRange(model.index(3, 0), model.index(3, 2))
selection2 = QItemSelection()
selection2.append(range2)

# 合并到第一个选择区域
selection.merge(selection2)
print("合并后的范围数量:", selection.count())  # 2

​与 QItemSelectionModel 结合使用

QItemSelectionModel 是管理视图(如 QTableView)中选中状态的核心类。通过信号 selectionChanged 可以捕获用户的选中操作。

from PyQt5.QtWidgets import QTableView, QApplication
from PyQt5.QtCore import QItemSelectionModel

class MyTableView(QTableView):
    def __init__(self):
        super().__init__()
        # 初始化模型(假设已设置)
        self.setModel(...)
        
        # 获取选择模型并连接信号
        self.selectionModel().selectionChanged.connect(self.handle_selection)

    def handle_selection(self, selected: QItemSelection, deselected: QItemSelection):
        # 处理新增选中区域
        for range in selected:
            top_left = range.topLeft()
            bottom_right = range.bottomRight()
            print(f"选中范围: 行 {top_left.row()}-{bottom_right.row()}, 列 {top_left.column()}-{bottom_right.column()}")

app = QApplication([])
window = MyTableView()
window.show()
app.exec_()

​应用场景

​注意事项

通过 ​QItemSelection,可以高效管理复杂的用户选择行为,为模型/视图应用提供灵活的数据交互能力。

到此这篇关于PyQt5 QItemSelection类使用小结的文章就介绍到这了,更多相关PyQt5 QItemSelection内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文