在两个单独的 QTableWidgets 之间拖放行
Posted
技术标签:
【中文标题】在两个单独的 QTableWidgets 之间拖放行【英文标题】:Drag and Dropping Rows between two separate QTableWidgets 【发布时间】:2016-04-04 16:26:26 【问题描述】:背景:
我的Main Window
上有两个单独的QTableWidget
s。这两者都是在python中动态添加的。我已经实现了pyqt代码,可以在three_pineapples解决方案here下找到。
我的问题
我希望能够将表格行从一个表格拖放到另一个表格。例如:
如果我尝试将项目 B 从 左表 拖到 右表
这就是结果
关于如何获得这种期望行为的任何建议?
【问题讨论】:
【参考方案1】:我看了@three_pineapples 的代码,有一半没看懂就删掉了。适用于多行选择。
import sys
from PyQt4.QtGui import *
class TableWidgetDragRows(QTableWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setDragEnabled(True)
self.setAcceptDrops(True)
self.setSelectionBehavior(QAbstractItemView.SelectRows)
self.setDragDropOverwriteMode(False)
# self.setSelectionMode(QAbstractItemView.SingleSelection)
self.last_drop_row = None
# Override this method to get the correct row index for insertion
def dropMimeData(self, row, col, mimeData, action):
self.last_drop_row = row
return True
def dropEvent(self, event):
# The QTableWidget from which selected rows will be moved
sender = event.source()
# Default dropEvent method fires dropMimeData with appropriate parameters (we're interested in the row index).
super().dropEvent(event)
# Now we know where to insert selected row(s)
dropRow = self.last_drop_row
selectedRows = sender.getselectedRowsFast()
# Allocate space for transfer
for _ in selectedRows:
self.insertRow(dropRow)
# if sender == receiver (self), after creating new empty rows selected rows might change their locations
sel_rows_offsets = [0 if self != sender or srow < dropRow else len(selectedRows) for srow in selectedRows]
selectedRows = [row + offset for row, offset in zip(selectedRows, sel_rows_offsets)]
# copy content of selected rows into empty ones
for i, srow in enumerate(selectedRows):
for j in range(self.columnCount()):
item = sender.item(srow, j)
if item:
source = QTableWidgetItem(item)
self.setItem(dropRow + i, j, source)
# delete selected rows
for srow in reversed(selectedRows):
sender.removeRow(srow)
event.accept()
def getselectedRowsFast(self):
selectedRows = []
for item in self.selectedItems():
if item.row() not in selectedRows:
selectedRows.append(item.row())
selectedRows.sort()
return selectedRows
class Window(QWidget):
def __init__(self):
super().__init__()
layout = QHBoxLayout()
self.setLayout(layout)
self.table_widgets = []
for _ in range(3):
tw = TableWidgetDragRows()
tw.setColumnCount(2)
tw.setHorizontalHeaderLabels(['Colour', 'Model'])
self.table_widgets.append(tw)
layout.addWidget(tw)
filled_widget = self.table_widgets[0]
items = [('Red', 'Toyota'), ('Blue', 'RV'), ('Green', 'Beetle')]
for i, (colour, model) in enumerate(items):
c = QTableWidgetItem(colour)
m = QTableWidgetItem(model)
filled_widget.insertRow(filled_widget.rowCount())
filled_widget.setItem(i, 0, c)
filled_widget.setItem(i, 1, m)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
【讨论】:
这似乎可行,但是我建议您在创建和设置QTableWidgetItem
之前添加一个检查。此检查将简单地显示为:if(sender.item(srow,j) is not None):
否则,如果该行的一个单元格为空,则它们是删除时的主要数据丢失。感谢您的回答,我将其标记为正确。
@sudobangbang 感谢您的评论。我忽略了这个问题,它发生在 python 2 上,它默认使用旧的 PyQt API v1。支票已添加。以上是关于在两个单独的 QTableWidgets 之间拖放行的主要内容,如果未能解决你的问题,请参考以下文章