使 QTableWidgetItem 不可编辑,但仍然能够 select 部分字符串

Make QTableWidgetItem non-editable, but still able to select parts of a string

我有一个带有数据的 QTableWidget,我希望用户能够双击并复制文本的特定部分。我唯一想禁用的是用户更改该文本的能力,这意味着设置标志 ~Qt.ItemIsEditable 限制太多。我怎样才能在 PyQt5 中实现这个?

注意:此解决方案适用于继承自 QAbstractItemView 的各种 类,例如 QTableWidget 或 QTreeWidget。

一个可能的解决方案是通过委托将编辑器修改为只读。

class StyledItemDelegate(QStyledItemDelegate):
    def createEditor(self, *args):
        editor = super().createEditor(*args)
        if isinstance(editor, QLineEdit):
            editor.setReadOnly(True)
        return editor
delegate = StyledItemDelegate(view)
view.setItemDelegate(delegate)