QTableWidget:按Enter键时不要关闭编辑器

时间:2015-05-20 16:41:29

标签: qt qtableview qtablewidget qtablewidgetitem

我希望我的QTableWidget在编辑项目时按Enter键时触发编辑回调但是我希望编辑器保持激活状态 - 就像它会选择所有项目的内容一样,当你开始编辑单元格时

这样做的最佳方式是什么?

感谢您一看。

2 个答案:

答案 0 :(得分:2)

您应该修改表的项委托并使用事件过滤器来过滤掉Enter事件并实现自定义行为:

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;
  }
};

用法:

ui->tableWidget->setItemDelegate(new MyDelegate(this));

答案 1 :(得分:0)

PyQt5代码如下所示:

class GlyphCellItemDelegate(QStyledItemDelegate):
    def eventFilter(self, editor, event):
        if (event.type() == QEvent.KeyPress and event.key() == Qt.Key_Return):
            self.commitData.emit(editor)
            # Don't emit closeEditor, select contents instead
            editor.selectAll()
            return True
        return False