我正在开发一个 QAction,将剪贴板中的结构化文本粘贴到 QTableWidget 中。这是我当前的代码:
class PasteCellsAction(qt.QAction):
def __init__(self, table):
if not isinstance(table, qt.QTableWidget):
raise ValueError('CopySelectedCellsAction must be initialised ' +
'with a QTableWidget.')
super(PasteCellsAction, self).__init__(table)
self.table = table
self.setText("Paste")
self.setShortcut(qt.QKeySequence('Ctrl+V'))
self.triggered.connect(self.pasteCellFromClipboard)
def pasteCellFromClipboard(self):
"""Paste text from cipboard into the table.
If the text contains tabulations and
newlines, they are interpreted as column and row separators.
In such a case, the text is split into multiple texts to be paste
into multiple cells.
:return: *True* in case of success, *False* if pasting data failed.
"""
selected_idx = self.table.selectedIndexes()
if len(selected_idx) != 1:
msgBox = qt.QMessageBox(parent=self.table)
msgBox.setText("A single cell must be selected to paste data")
msgBox.exec_()
return False
selected_row = selected_idx[0].row()
selected_col = selected_idx[0].column()
qapp = qt.QApplication.instance()
clipboard_text = qapp.clipboard().text()
table_data = _parseTextAsTable(clipboard_text)
protected_cells = 0
out_of_range_cells = 0
# paste table data into cells, using selected cell as origin
for row in range(len(table_data)):
for col in range(len(table_data[row])):
if selected_row + row >= self.table.rowCount() or\
selected_col + col >= self.table.columnCount():
out_of_range_cells += 1
continue
item = self.table.item(selected_row + row,
selected_col + col)
# ignore empty strings
if table_data[row][col] != "":
if not item.flags() & qt.Qt.ItemIsEditable:
protected_cells += 1
continue
item.setText(table_data[row][col])
if protected_cells or out_of_range_cells:
msgBox = qt.QMessageBox(parent=self.table)
msg = "Some data could not be inserted, "
msg += "due to out-of-range or write-protected cells."
msgBox.setText(msg)
msgBox.exec_()
return False
return True
我想在将数据粘贴到单元格之前测试单元格是否可编辑,为此我使用 QTableWidget.item(row, col)
获取该项目,然后检查该项目的标志.
我的问题是 .item
方法对于空单元格返回 None
,因此我无法检查空单元格的标志。我的代码当前仅在粘贴区域中没有空单元格时才有效。
错误位于第 46 行(None
返回)和第 50 行(AttributeError: 'NoneType' 对象没有属性 'flags'
):
item = self.table.item(selected_row + row,
selected_col + col)
# ignore empty strings
if table_data[row][col] != "":
if not item.flags() & qt.Qt.ItemIsEditable:
...
除了检查项目的标志之外,还有其他方法可以确定单元格是否可编辑吗?
最佳答案
QTableWidget
a 的尺寸可以在不显式添加任何项目的情况下指定。在这种情况下,单元格将完全为空 - 即数据和项目都将为None
。如果用户编辑单元格,数据将被添加到表的模型中,并且将添加一个项目。即使输入的值为空字符串,也会发生这种情况。默认情况下,所有单元格都可以编辑,除非您采取明确的步骤将它们设为只读。
有多种方法可以使单元格只读 - 例如,setting the edit triggers ,或覆盖表的 edit方法。但是,如果您的 only 方法在各个表格小部件项目上显式设置标志,则您可以安全地假设没有项目的单元格既可编辑又为空。 (请注意,如果您直接通过表的模型而不是使用 setItem
设置数据,单元格仍会自动拥有一个项目)。
关于python - 在QTableWidget中,如何确定空单元格是否可编辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40765090/