簡體   English   中英

在QTableWidget中,如何確定空單元格是否可編輯?

[英]In a QTableWidget, how to determine if an empty cell is editable?

我正在進行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' object has no attribute '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 如果用戶編輯單元格,則數據將添加到表格的模型中,並添加一個項目。 即使輸入的值是空字符串,也會發生這種情況。 默認情況下,除非您采取明確的步驟將它們設置為只讀,否則所有單元格都是可編輯的。

有許多方法可以將單元格設置為只讀 - 例如, 設置編輯觸發器或覆蓋表格的編輯方法。 但是,如果您唯一的方法是在單個表窗口小部件項目上顯式設置標志,則可以安全地假設沒有項目的單元格既可編輯又為空。 (請注意,如果您通過表格模型直接設置數據而不是使用例如setItem ,則單元格仍將自動擁有一個項目)。

我找到了一個似乎有效的解決方案:當item()方法返回None時,創建一個新項並將其添加到表中。

我仍然懷疑是否存在這可能會修改寫保護單元的標志的風險。 我目前只是假設如果一個單元被寫保護,這意味着它必然已經包含一個項目。

            item = self.table.item(target_row,
                                   target_col)
            # item may not exist for empty cells
            if item is None:
                item = qt.QTableWidgetItem()
                self.table.setItem(target_row,
                                   target_col,
                                   item)
            # ignore empty strings
            if table_data[row_offset][col_offset] != "":
                if not item.flags() & qt.Qt.ItemIsEditable:
                    protected_cells += 1
                    continue
                item.setText(table_data[row_offset][col_offset])

編輯: target_row = selected_row + row_offset ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM