python - 从 QListView 中正确删除多选行

标签 python python-3.x pyqt pyqt5 qlistview

我在尝试从 QListView 中正确删除多个选定行时遇到问题。它可以正确地从上到下选择项目,但是当您从下到上选择多行时,它会在 View 中保留选定的行之一。

如何修复此问题,以便以用户选择的任何顺序正确删除所有选定的行?

示例:

按此顺序选择行会给出无效的解决方案: 5级、3级、2级

仅删除 Level2

将 self.listView.selectedIndexes() 中的项目更改为 : 与无法从上到下选择的情况相反。

from PyQt5 import QtCore, QtGui, QtWidgets
import sys,functools

class Window(QtWidgets.QMainWindow):
    def __init__(self, parent = None):
        super(Window,self).__init__(parent)
        self.setCentralWidget(QtWidgets.QWidget(self))
        self.setWindowTitle('GUI')
        mainlayout = QtWidgets.QVBoxLayout()
        #Information for widgets
        self.items = {'Level1':1,'Level2':2,'Level3':3,'Level4':4,'Level5':5,'Level6':6}
        #LineEdit1
        self.button = QtWidgets.QPushButton()
        self.button.setText('Remove Selected Items')
        firstBox = QtWidgets.QHBoxLayout()
        firstBox.addWidget(self.button)
        #ListView
        self.listView = QtWidgets.QListView()
        self.listView.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
        secondBox = QtWidgets.QVBoxLayout()
        secondBox.addWidget(self.listView)

        #Add Layouts
        mainlayout.addLayout(firstBox)
        mainlayout.addLayout(secondBox)
        self.centralWidget().setLayout(mainlayout)
        #Model
        self.model = QtGui.QStandardItemModel()
        self.listView.setModel(self.model)

        self.button.clicked.connect(functools.partial(self.selecteditems,self.model))
        self.fillModel(self.model)

    def fillModel(self,model):
        for level in self.items:
            item = QtGui.QStandardItem(str(level))
            model.appendRow(item)

    def selecteditems(self,model):
        if len(self.listView.selectedIndexes()) > 1:
            for items in reversed(self.listView.selectedIndexes()):
                model.takeRow(items.row()) #works correctly selecting items from top to bottom, but doesn't work when selecting bottom to top
def main():
    app = QtWidgets.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())



if __name__ == '__main__':
    main()

最佳答案

您还可以仅使用反转排序:

def selecteditems(self,model):
    if len(self.listView.selectedIndexes()) > 1:
        for items in reversed(sorted(self.listView.selectedIndexes())):
            model.takeRow(items.row()) 

关于python - 从 QListView 中正确删除多选行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57185757/

相关文章:

python - Matplotlib 传输多个艺术家

python - 如何使用 for 循环和通过使用追加从预先存在的列表中删除项目?

python - PyQt5:如何通过单击按钮打开新对话框

python - 我怎样才能在 pyside QWidget 中有一个透明的背景,但保持它的 child 不透明

python - PyQt:如何从 QQmlApplicationEngine 获取根对象

python - 从文件名中获取单词,然后压缩并存储为变量

python - 在 matplotlib 中跨子图绘制分界线

python - 如何在python中用单个反斜杠替换双反斜杠?

python - 在 python 3.4.3 上安装软件包时出现奇怪的错误

安装了Python 3,运行时出错