在 Python 中切换 QTableWidget 的可编辑性

Toggle the editability of a QTableWidget in Python

我希望能够 table 将以前未被编辑的单元格table 编辑table。然后 control/toggle 通过将函数附加到按钮来 table 的可编辑性。

from PyQt5 import QtCore, QtWidgets


class ReadOnlyDelegate(QtWidgets.QStyledItemDelegate):
    def createEditor(self, parent, option, index):
        # last column
        #if index.column() == (index.model().columnCount() - 1):
        return super().createEditor(parent, option, index)


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        table_widget = QtWidgets.QTableWidget(4, 3)
        self.setCentralWidget(table_widget)
        
        
        item = QTableWidgetItem(str('wait'))
        item_2 = QTableWidgetItem(str('wait'))
        item_3 = QTableWidgetItem(str('wait'))
        item_4 = QTableWidgetItem(str('wait'))
        item_5 = QTableWidgetItem(str('wait'))
    
        # execute the line below to every item you need locked
        item.setFlags(QtCore.Qt.ItemIsEnabled)
        item_2.setFlags(QtCore.Qt.ItemIsEnabled)
        item_3.setFlags(QtCore.Qt.ItemIsEnabled)
        item_4.setFlags(QtCore.Qt.ItemIsEnabled)
        item_5.setFlags(QtCore.Qt.ItemIsEnabled)
        
        
        
        table_widget.setItem(0, 1, item)
        table_widget.setItem(1, 1, item_2)
        table_widget.setItem(1, 2, item_3)
        table_widget.setItem(3, 1, item_4)
        table_widget.setItem(4, 1, item_5)
        

        delegate = ReadOnlyDelegate(table_widget)
        table_widget.setItemDelegate(delegate)
        
        

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.resize(320, 240)
    w.show()
    sys.exit(app.exec_())

在上面的示例中,即使我 运行 整个 table 的代表在创建和插入那些之后,具有未编辑的项目的单元格 table 仍然保持这种状态项目。有没有办法使整个 table 包括 un-editable 单元格 editable?

模型方法以简单的方式解决了这类问题:您可以为特定项目或整个 table 指定标志作为

的函数
from PyQt5 import QtWidgets, QtCore, QtGui

class Model(QtGui.QStandardItemModel):

    def __init__(self, rows, columns, parent = None):
        super().__init__(rows, columns, parent)
        self._editable = True

    def flags(self, index: QtCore.QModelIndex) -> QtCore.Qt.ItemFlags:
        flags = super().flags(index)
        if not self._editable:
            flags = flags &~ QtCore.Qt.ItemIsEditable
        return flags

    def setEditable(self, editable):
        self._editable = editable

if __name__ == "__main__":
    app = QtWidgets.QApplication([])

    model = Model(4, 3)

    widget = QtWidgets.QWidget()
    layout = QtWidgets.QVBoxLayout()
    
    view = QtWidgets.QTableView()
    view.setModel(model)
    view.show()

    checkBox = QtWidgets.QCheckBox("Editable")
    checkBox.setChecked(True)
    checkBox.clicked.connect(model.setEditable)

    layout.addWidget(view)
    layout.addWidget(checkBox)
    widget.setLayout(layout)
    widget.show()
    
    app.exec()