You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现QTableView选中状态反转并删除选中行?

实现反转选中并删除选中行的PyQt5方案

嘿,这需求不难实现,我给你写好完整可运行代码并拆解关键步骤哈:

完整代码

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

app = QApplication([])

class Dialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("反转选中并删除")
        
        # 创建表格视图和数据模型
        self.table_view = QTableView()
        self.model = QStandardItemModel(5, 2)  # 初始化5行2列的测试表格
        # 填充测试数据,方便直观测试效果
        for row in range(5):
            for col in range(2):
                item = QStandardItem(f"行{row}列{col}")
                self.model.setItem(row, col, item)
        self.table_view.setModel(self.model)
        
        # 创建功能按钮并绑定处理函数
        self.reverse_delete_btn = QPushButton("反转选中状态并删除选中行")
        self.reverse_delete_btn.clicked.connect(self.handle_reverse_and_delete)
        
        # 布局组装
        main_layout = QVBoxLayout()
        main_layout.addWidget(self.table_view)
        main_layout.addWidget(self.reverse_delete_btn)
        self.setLayout(main_layout)
        
    def handle_reverse_and_delete(self):
        # 1. 反转所有行的选中状态
        selection_model = self.table_view.selectionModel()
        total_rows = self.model.rowCount()
        for row_idx in range(total_rows):
            # 取每行第一列的索引即可操作整行选中状态(默认整行选中模式)
            row_index = self.model.index(row_idx, 0)
            is_selected = selection_model.isSelected(row_index)
            # 切换选中状态:选中→取消,未选中→选中
            if is_selected:
                selection_model.select(row_index, QItemSelectionModel.Deselect)
            else:
                selection_model.select(row_index, QItemSelectionModel.Select)
        
        # 2. 删除当前选中的行(必须从后往前删,避免索引混乱)
        # 先收集所有选中行的索引,然后倒序排序
        selected_rows = sorted([idx.row() for idx in selection_model.selectedRows()], reverse=True)
        for row in selected_rows:
            self.model.removeRow(row)

# 运行程序
dialog = Dialog()
dialog.show()
app.exec_()

关键步骤拆解

  • 数据模型准备:用QStandardItemModel作为表格的数据载体,这是PyQt中操作表格数据最常用的方式,方便后续的行删除操作。我提前填充了测试数据,你可以直接运行看到效果。
  • 反转选中状态:通过table_view.selectionModel()获取表格的选中管理对象,遍历每一行,用isSelected()判断当前行的选中状态,再调用select()方法切换状态(Deselect取消选中,Select设置选中)。
  • 安全删除行:收集所有选中行的索引后,一定要倒序删除!因为如果从前往后删,删除前面的行后,后面的行索引会自动前移,导致原本记录的行号对应错误,倒序删除就能完美避免这个问题。

内容的提问来源于stack exchange,提问作者alphanumeric

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:25:15