Reputation: 3346
Here are 2 answers for capturing the key press event for QTableWidget. How to create a SIGNAL for QTableWidget from keyboard?
Follow the way above, I can "hook" key press event, When I press space, the background color becomes red.
However, it only works for a selected cell, but not for a in-editing cell.
When it's in editing state, the 2 ways both fail. I can type space freely.
Upvotes: 0
Views: 985
Reputation: 4698
When it's in "editing state" there is editor widget atop QTableWidget
(item delegate) which receives key events, and since it's on top you can't see cell content and cell background behind it. But you can access and "hook" this events by setting QAbstractItemDelegate
to QTableWidget
.
// itemdelegate.h
class ItemDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
explicit ItemDelegate(QObject *parent = nullptr) : QStyledItemDelegate(parent)
{
}
bool eventFilter(QObject *object, QEvent *event) override
{
if (event->type() == QEvent::KeyPress) {
QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
if (keyEvent->key() == Qt::Key_Space) {
qDebug() << "space pressed";
}
}
return false;
}
};
// main.cpp
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTableWidget* widget = new QTableWidget();
widget->setColumnCount(2);
widget->setRowCount(2);
widget->setItemDelegate(new ItemDelegate(widget));
widget->show();
return a.exec();
}
Upvotes: 1