效果如下:
代码量很少,QTableWidget主要实现了代理ItemDelegate, 返回一个自定义的QLineEdit
再到QLineEdit中重新实现下键盘事件,捕获输入。
主要代码(QTableWidget代理):
HotkeyItemDelegate.h
class HotkeyItemDelegate : public QItemDelegate
{
Q_OBJECT
public:
HotkeyItemDelegate(QObject *parent = nullptr);
~HotkeyItemDelegate();
virtual QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
virtual void setEditorData(QWidget *editor, const QModelIndex &index) const;
virtual void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const;
virtual void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const;
};
HotkeyItemDelegate.cpp 代理实现
HotkeyItemDelegate::HotkeyItemDelegate(QObject *parent)
: QItemDelegate(parent)
{
}
HotkeyItemDelegate::~HotkeyItemDelegate()
{
}
QWidget *HotkeyItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
HotkeyLineEdit *lineEdit = new HotkeyLineEdit(parent);
return lineEdit;
}
void HotkeyItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
HotkeyLineEdit *control = dynamic_cast<HotkeyLineEdit *>(editor);
control->setText(index.model()->data(index, Qt::EditRole).toString());
}
void HotkeyItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
HotkeyLineEdit *control = dynamic_cast<HotkeyLineEdit*>(editor);
model->setData(index, control->text(), Qt::EditRole);
}
void HotkeyItemDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
editor->setGeometry(option.rect);
}
自定义QLineEdit具体实现:
HotkeyLineEdit.h
class HotkeyLineEdit : public QLineEdit
{
Q_OBJECT
public:
HotkeyLineEdit(QWidget *parent = nullptr);
~HotkeyLineEdit();
protected:
virtual void keyPressEvent(QKeyEvent *);
};
HotkeyLineEdit.cpp
HotkeyLineEdit::HotkeyLineEdit(QWidget *parent)
: QLineEdit(parent)
{
}
HotkeyLineEdit::~HotkeyLineEdit()
{
}
void HotkeyLineEdit::keyPressEvent(QKeyEvent *event)
{
//捕获输入的键, 除了A-Z以及Ctrl/Shift,其它都无视
if (event->key() >= Qt::Key_A && event->key() <= Qt::Key_Z)
{
QChar strKey = (QChar)event->key();
if (event->modifiers() == Qt::ControlModifier)
{
this->setText(QString("CTRL+%0").arg(strKey));
}
else if (event->modifiers() == Qt::ShiftModifier)
{
this->setText(QString("SHIFT+%0").arg(strKey));
}
else if (event->modifiers() == (Qt::ShiftModifier | Qt::ControlModifier))
{
this->setText(QString("CTRL+SHIFT+%0").arg(strKey));
}
}
}
主要是用在一些软件高级设置中的自己输入快捷键的情况下。