Zorobay
Zorobay

Reputation: 649

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

I have a QTableWidget with data that I would like the user to be able to double-click on, and copy a specific part of the text. The only thing I want to disable is the user's ability to change that text, meaning that setting the flag ~Qt.ItemIsEditable is too restrictive. How can I achieve this in PyQt5?

Upvotes: 1

Views: 672

Answers (1)

eyllanesc
eyllanesc

Reputation: 243897

Note: This solution works for all kinds of classes that inherit from QAbstractItemView like QTableWidget or QTreeWidget.

A possible solution is to use a modify the editor to be read-only through a delegate.

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)

Upvotes: 2

Related Questions