当用户通过在Excel中选择整个列进行复制时,我将问题从Excel中粘贴到QTableView中,实际上将整个Excel工作表中的每一行都放在剪贴板上。以下是我的QTableView粘贴代码(请注意,这是使用PyQt的Python,但原理与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()找到)。
是否有任何方法可以比制表符分隔的文本或其他内容更有效地从剪贴板中获取复制的列?或者,当剪贴板上的字符串大小是一个任意大的长度时,我应该抛出一个错误吗?
答案 0 :(得分:0)
不熟悉QTableView,但我在VBA Excel中有类似的经验;显然你打到了表格的底部。
中,Excel 97 - 2003中有65,536行,2007 +中有1048576行。检查行数,2个值中的任何一个表示您刚刚遍历整个列而没有点击任何包含值的单元格,因此该列为空。