Zhang
Zhang

Reputation: 3346

How do I capture the key press event for an edit cell of a QTableWidget?

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.

enter image description here

However, it only works for a selected cell, but not for a in-editing cell.

enter image description here

When it's in editing state, the 2 ways both fail. I can type space freely.

Upvotes: 0

Views: 985

Answers (1)

mugiseyebrows
mugiseyebrows

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

Related Questions