qtablewidget鼠标拖拽
时间: 2023-10-04 14:07:29 浏览: 92
您可以通过实现`QTableWidget`的`dragEnterEvent`、`dragMoveEvent`和`dropEvent`事件来实现鼠标拖拽。具体步骤如下:
1. 在`QTableWidget`的构造函数中设置可拖拽属性:
```python
self.setDragEnabled(True)
```
2. 实现`dragEnterEvent`和`dragMoveEvent`方法,将拖拽的数据类型设置为`QTableWidgetItem`:
```python
def dragEnterEvent(self, event):
if event.mimeData().hasFormat('application/x-qabstractitemmodeldatalist'):
event.accept()
else:
event.ignore()
def dragMoveEvent(self, event):
if event.mimeData().hasFormat('application/x-qabstractitemmodeldatalist'):
event.accept()
else:
event.ignore()
```
3. 实现`dropEvent`方法,获取拖拽的数据并插入到表格中:
```python
def dropEvent(self, event):
if event.mimeData().hasFormat('application/x-qabstractitemmodeldatalist'):
data = event.mimeData().data('application/x-qabstractitemmodeldatalist')
stream = QDataStream(data, QIODevice.ReadOnly)
row, column, _ = stream.readInt32(), stream.readInt32(), stream.readInt32()
items = []
while not stream.atEnd():
text = stream.readQString()
item = QTableWidgetItem(text)
items.append(item)
for i, item in enumerate(items):
self.setItem(row + i, column, item)
event.accept()
else:
event.ignore()
```
这样就可以实现`QTableWidget`的鼠标拖拽功能了。
阅读全文