我能够轻松地在QListWidget上拖放工作,我为它分配了单独的项目,但我已经切换到QListView和模型/视图模式,我似乎无法让它工作。我只对允许用户重新排序列表中的对象感兴趣,但我不希望他们实际编辑这些对象(除了前面提到的重新排序)。这就是我所做的:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class AlgorithmListControl(QListView):
def __init__(self, parent = None):
super(AlgorithmListControl, self).__init__(parent)
self.parent = parent
self.setAcceptDrops(True)
self.setDragEnabled(True)
self.setDragDropMode(QAbstractItemView.InternalMove)
self.setDefaultDropAction(Qt.MoveAction)
self.setDropIndicatorShown(True)
对于数据模型,我只是声明一个继承自QAbstractListModel的类,实现“rowCount”和“data”方法,向其添加一些对象,然后通过“myAlgorithmList.setModel”将其指定为上述类的模型。 (基于myModel)”。到目前为止一切正常,我可以看到列表中的对象,它们的图标显示为正确,顺序正确等等。但是我无法通过拖放重新排序它们。当我尝试拖动项目时,没有视觉指示拖动模式已启动,并且(当然)如果我尝试放下则不会发生任何事情。好像没有设置拖放模式。我错过了什么?我已经狩猎了一段时间,没有任何东西在向我跳来跳去。这可能与模型的可编辑性有关吗?我在模型中添加了以下内容,但没有效果:
def flags(self, index):
return (Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable)
抓住我的头。
更新:我已将flags语句更改为以下内容:
def flags(self, index):
if index.isValid():
return Qt.ItemIsSelectable | Qt.ItemIsDragEnabled | Qt.ItemIsEnabled
return Qt.ItemIsSelectable | Qt.ItemIsDragEnabled | Qt.ItemIsDropEnabled | Qt.ItemIsEnabled
我现在能够至少拖动一个项目,但在发布时没有任何反应。
更新:阅读评论后,我正在添加模型的代码。显然问题存在于那里的某个地方。我已经开始实现模型的“insertRows()”方法,但是如果我在该方法中放置一个断点并在运行时尝试拖放操作,那么该方法显然永远不会被调用。我也不确定基于“insertRows()”方法中的拖放重新排序列表的逻辑。任何帮助非常感谢:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class AlgorithmSequenceModel(QAbstractListModel):
def __init__(self, parent = None):
super(AlgorithmSequenceModel, self).__init__(parent)
self.parent = parent
# Instantiate an empty list for holding the list of algorithm objects in the proper sequence:
self.algorithms = list()
# Do I need this?: self.setSupportedDragActions(Qt.MoveAction)
def rowCount(self, parent):
# Return the number of algorithms in the current sequence:
return len(self.algorithms)
def flags(self, index):
if index.isValid():
return Qt.ItemIsSelectable | Qt.ItemIsDragEnabled | Qt.ItemIsEnabled | Qt.ItemIsDropEnabled
return Qt.ItemIsSelectable | Qt.ItemIsDragEnabled | Qt.ItemIsDropEnabled | Qt.ItemIsEnabled
def data(self, index, role):
# Check the role that's being queried:
if role == Qt.DisplayRole:
# Retrieve the algorithm and return its name:
row = index.row()
return self.algorithms[row].getName()
if role == Qt.DecorationRole:
# Retrieve the algorithm and return the icon object reflecting its current state:
row = index.row()
return self.algorithms[row].getCurrentStateIcon()
def setData(self, index, value, role = Qt.EditRole):
# Data is not editable by user.
pass
def insertRows(self, position, rows, parent):
self.beginInsertRows()
# Very uncertain how to implement reordering here. Dragged item needs to be removed from its original location and inserted in new location
self.endInsertRows()
def addAlgorithm(self, algorithm):
# Append the algorithm to the end of list:
self.algorithms.append(algorithm)