python - 在QTableWidget中,如何确定空单元格是否可编辑?

标签 python qt pyqt qtablewidget

我正在开发一个 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/

相关文章:

python - 如何在 readthedocs 上正确设置 PyQt5 导入?

python - 使用自定义模型编辑 QTreeView 中的第二列不显示编辑器

python - 如何有一个命令运行的百分比机会

python - python 中的 zip(),如何使用静态值

python - 如何在python脚本的if条件下避免硬编码

c++ - 在 Qt 中声明 const 并从 2 个不同的类访问

python - multiprocessing 会是这个操作的一个很好的解决方案吗?

c++ - QMediaPlayer 不产生音频

QT4:是否可以使QListView平滑滚动?

qt - 带有 html 富文本委托(delegate)的 PyQt listview 将文本位移出位置(包括图片和代码)