【发布时间】:2013-05-07 22:03:35
【问题描述】:
当用户通过在 Excel 中选择一整列进行复制时,我在从 Excel 粘贴到 QTableView 时遇到问题,基本上将整个 Excel 工作表的每一行都放在剪贴板上的选定列中。以下是我的QTableView粘贴代码(请注意,这是在Python中使用PyQt但原理与C++相同)。
def paste(self):
model=self.model()
pasteString=QtGui.QApplication.clipboard().text()
rows=pasteString.split('\n')
numRows=len(rows)
numCols=rows[0].count('\t')+1
selectionRanges=self.selectionModel().selection()
#make sure we only have one selection range and not non-contiguous selections
if len(selectionRanges)==1:
topLeftIndex=selectionRanges[0].topLeft()
selColumn=topLeftIndex.column()
selRow=topLeftIndex.row()
if selColumn+numCols>model.columnCount():
#the number of columns we have to paste, starting at the selected cell, go beyond how many columns exist.
#insert the amount of columns we need to accomodate the paste
model.insertColumns(model.columnCount(), numCols-(model.columnCount()-selColumn))
if selRow+numRows>model.rowCount():
#the number of rows we have to paste, starting at the selected cell, go beyond how many rows exist.
#insert the amount of rows we need to accomodate the paste
model.insertRows(model.rowCount(), numRows-(model.rowCount()-selRow))
#block signals so that the "dataChanged" signal from setData doesn't update the view for every cell we set
model.blockSignals(True)
for row in xrange(numRows):
columns=rows[row].split('\t')
[model.setData(model.createIndex(selRow+row, selColumn+col), QVariant(columns[col])) for col in xrange(len(columns))]
#unblock the signal and emit dataChangesd ourselves to update all the view at once
model.blockSignals(False)
model.dataChanged.emit(topLeftIndex, model.createIndex(selRow+numRows, selColumn+numCols))
当用户在 Excel 中选择了一堆单元格并复制了这些单元格时,这一切都可以正常工作。当他们选择一整列时它会崩溃,因为pasteString 然后变成超过 1048576 个字符的长度(通过选择其标题并复制突出显示完全空的 Excel 列时打印 pasteString.size() 可以找到)。
有没有比制表符分隔的文本更有效地从剪贴板获取复制的列?还是当剪贴板上的字符串长度任意大时,我应该抛出一个错误?
【问题讨论】:
标签: excel qt pyqt paste qtableview