0

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.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Zhang
  • 3,030
  • 2
  • 14
  • 31
  • For the inline editor, that has keyboard focus, you had to catch the space bar there (i.e. overload the key events). An [event filter](https://doc.qt.io/qt-5/eventsandfilters.html#event-filters) might be a 2nd option. – Scheff's Cat Dec 10 '20 at 10:05
  • How about a [mcve]? – Scheff's Cat Dec 10 '20 at 10:06
  • 2
    One way would be to implement your own 'editor' widget and create/use an item delegate that returns an instance of that editor from [`QAbstractItemDelegate::createEditor`](https://doc.qt.io/qt-5/qabstractitemdelegate.html#createEditor). – G.M. Dec 10 '20 at 11:26

1 Answers1

1

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();
}
mugiseyebrows
  • 4,138
  • 1
  • 14
  • 15