backseat
backseat

Reputation: 213

Don't select text in QTableWidget cell when editing

My app allows double-clicking on a QTableWidget cell to edit the content. However, when I double-click on a cell, the existing content is selected.

How can I allow a cell's content to be edited without having the existing text automatically selected?

Upvotes: 1

Views: 254

Answers (1)

musicamante
musicamante

Reputation: 48231

Qt item views automatically call selectAll() when an editor is created and it's a QLineEdit or a Q[Double]SpinBox.

Since the call to selectAll() is done after the editor is created, a simple solution would be to connect to the selectionChanged signal and deselect the text automatically. This can be done in an item delegate that would just override createEditor().

Note that this must be done only once, otherwise any user selection would become impossible. This also means that the signal must be disconnected immediately, and before deselecting (otherwise the function would be called again).

class NoSelectDelegate(QStyledItemDelegate):
    def createEditor(self, parent, option, index):
        editor = super().createEditor(parent, option, index)
        if isinstance(editor, (QLineEdit, QSpinBox, QDoubleSpinBox)):
            def deselect():
                # Important! First disconnect, otherwise editor.deselect()
                # will call again this function
                editor.selectionChanged.disconnect(deselect)
                editor.deselect()
            editor.selectionChanged.connect(deselect)
        return editor


# ...

table.setItemDelegate(NoSelectDelegate(table))

Upvotes: 2

Related Questions