I would like my QTableWidget
to trigger the edition callbacks when pressing Enter while editing item BUT I would like the editor to remain activated – like it would just select all of the item’s content like when you start editing the cell.
What is the best way to do this?
Thanks for having a look here.
You should modify the table's item delegate and use event filters to filter out Enter event and implement custom behavior:
class MyDelegate : public QStyledItemDelegate {
public:
MyDelegate(QObject* parent) : QStyledItemDelegate(parent) {}
QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option,
const QModelIndex& index) const {
QWidget* editor = QStyledItemDelegate::createEditor(parent, option, index);
editor->installEventFilter(const_cast<MyDelegate*>(this));
return editor;
}
bool eventFilter(QObject* object, QEvent* event) {
QWidget* editor = qobject_cast<QWidget*>(object);
if (editor && event->type() == QEvent::KeyPress) {
QKeyEvent* key_event = static_cast<QKeyEvent*>(event);
if (key_event->key() == Qt::Key_Return) {
emit commitData(editor); //save changes
QLineEdit* line_edit = qobject_cast<QLineEdit*>(editor);
if (line_edit) {
line_edit->selectAll();
}
return true;
}
}
return false;
}
};
Usage:
ui->tableWidget->setItemDelegate(new MyDelegate(this));