【发布时间】:2019-04-18 05:23:10
【问题描述】:
我正在开发 QTableView 中的自定义拖放实现。当我将一个单元格拖放到另一个单元格上时,我想根据拖动的内容和放置的位置手动更改模型中的一些数据。我怎样才能做到这一点?我一直在阅读所有 Qt 文档,但完全迷失了方向,尤其是拖放时,C++ 到 PyQt 的转换似乎不太直观。
基本上我需要的是当我放下时,我想知道最初拖动了哪些单元格,以及它们被放置在哪里。我的困惑似乎在于 QMimeData。据我所知,拖动开始时,拖动事件接收到正确的 MIME 数据,但我不知道如何在 PyQt 中获取它(过去能够用文本和 url 做这种事情,但我当涉及到项目视图时,我迷路了)。我还需要知道我要去哪里。我想我可以做一个“光标位置的项目”,但我假设这个数据已经存在于 drop 事件中,我只需要弄清楚如何查询它。
这是一个简单的例子:
import sys
from PyQt4 import QtGui, QtCore
class TableView(QtGui.QTableView):
def __init__(self, parent=None):
QtGui.QTreeWidget.__init__(self, parent)
self.setDragEnabled(True)
self.setDropIndicatorShow(True)
self.setDragDropMode(QtGui.QAbstractItemView.DragDrop)
self.setDragDropOverwriteMode(False)
self.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
def dragEnterEvent(self, event):
event.accept()
def dropEvent(self, event):
# I want to do cool things with the dragged cells, and I need to know where they dropped!
print(event.mimeData().formats()) # this tells me that I shuld get some sort of "qabstractitemmodeldatalist". Sounds promising...
print(event.mimeData().data("application/x-qabstractitemmodeldatalist")) # this gives me an interesting looking QByteArray but I have no idea what to do with it...
event.accept()
class Dialog(QtGui.QDialog):
def __init__(self):
super(Dialog, self).__init__()
model = QtGui.QStandardItemModel(self)
model.insertRow(0, QtGui.QStandardItem("C"))
model.insertRow(0, QtGui.QStandardItem("B"))
model.insertRow(0, QtGui.QStandardItem("A"))
table = TableView(self)
table.setModel(model)
app = QtGui.QApplication(sys.argv)
ex = Dialog()
ex.show()
sys.exit(app.exec_())
【问题讨论】:
标签: python pyqt drag-and-drop pyqt4