qtableview text edit

pyqt, qt, qtableview

Solution

Not sure if there is a simpler way, but you can write your own item delegate which creates a QLineEdit. When updating the editor with model's data you deselect the text and possibly move the cursor to the beginning. The delegate would be something like this (I don't have a Qt installation available right now so I can't test it, but the idea should work):

QWidget * MyDelegate::createEditor(QWidget *parent,
        const QStyleOptionViewItem & option,
        const QModelIndex & index) const
{
    // Just creates a plain line edit.
    QLineEdit *editor = new QLineEdit(parent);
    return editor;
}

void MyDelegate::setEditorData(QWidget *editor,
        const QModelIndex &index) const
{
    // Fetch current data from model.
    QString value = index.model()->data(index, Qt::EditRole).toString();

    // Set line edit text to current data.
    QLineEdit * lineEdit = static_cast<QLineEdit*>(editor);
    lineEdit->setText(value);

    // Deselect text.
    lineEdit->deselect();

    // Move the cursor to the beginning.
    lineEdit->setCursorPosition(0);
}

void MyDelegate::setModelData(QWidget *editor,
        QAbstractItemModel *model,
        const QModelIndex &index) const
{
    // Set the model data with the text in line edit.
    QLineEdit * lineEdit = static_cast<QLineEdit*>(editor);
    QString value = lineEdit.text();
    model->setData(index, value, Qt::EditRole);
}

If you haven't used delegates before in Qt documentation there is a useful example.

Problem

I'm writing a program with PyQt. I use QTableView to display data. The problem is when I trigger the edit(for example press F2) of a cell, the text in the cell is all selected(highlighted) by default. It's not convenience because I want to modify the text but not rewrite them all. So I want to know if there is any function to change the behavior? Thank you

Original source