首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

从QListView中正确删除多选的行

,可以按照以下步骤进行操作:

  1. 获取选中的行索引:使用QListView的selectedIndexes()方法可以获取到当前选中的所有行的索引。
  2. 删除选中的行:遍历选中的行索引,使用QListView的model()方法获取到QAbstractItemModel对象,然后调用QAbstractItemModel的removeRow()方法来删除选中的行。
  3. 刷新视图:删除行后,需要调用QListView的update()方法或者重新设置model来刷新视图,使得删除的行在界面上消失。

下面是一个示例代码:

代码语言:txt
复制
# 导入必要的模块
from PyQt5.QtWidgets import QApplication, QMainWindow, QListView, QMessageBox
from PyQt5.QtCore import Qt

# 创建主窗口类
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        # 创建QListView对象
        self.list_view = QListView(self)
        self.setCentralWidget(self.list_view)

        # 创建模型并设置给QListView
        self.model = QStandardItemModel(self)
        self.list_view.setModel(self.model)

        # 添加一些示例数据
        for i in range(5):
            item = QStandardItem(f"Item {i}")
            self.model.appendRow(item)

        # 设置QListView为多选模式
        self.list_view.setSelectionMode(QListView.ExtendedSelection)

        # 添加删除按钮,并绑定点击事件
        self.delete_button = QPushButton("删除选中行", self)
        self.delete_button.clicked.connect(self.delete_selected_rows)

    # 删除选中的行
    def delete_selected_rows(self):
        # 获取选中的行索引
        selected_indexes = self.list_view.selectedIndexes()

        # 判断是否有选中的行
        if len(selected_indexes) == 0:
            QMessageBox.warning(self, "警告", "请先选择要删除的行")
            return

        # 删除选中的行
        for index in selected_indexes:
            self.model.removeRow(index.row())

        # 刷新视图
        self.list_view.update()

# 创建应用程序对象
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()

在上述示例代码中,我们创建了一个主窗口类MainWindow,其中包含一个QListView用于显示数据,并设置为多选模式。我们还添加了一个删除按钮,点击按钮时会调用delete_selected_rows()方法来删除选中的行。

在delete_selected_rows()方法中,我们首先使用selectedIndexes()方法获取到选中的行索引,然后遍历选中的行索引,调用model的removeRow()方法来删除选中的行。最后调用update()方法刷新视图。

这样,就可以从QListView中正确删除多选的行了。

注意:以上示例代码中使用的是PyQt5库,如果你使用的是其他的GUI库,可以根据相应的库文档进行相应的调整。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券