I have a table and move around inside with left, right, up, down buttons. Now I need to create a SIGNAL when I stay in a certain cell and press SPACE button. This SIGNAL should bring also the coordinate of that cell. I tried with standard signals of QTableWidget but it does not work. How can I solve this?
Asked
Active
Viewed 3,405 times
3
-
Try to achieve it by reimplement [keyPressEvent()](http://doc.qt.io/qt-5/qabstractitemview.html#keyPressEvent), when you are on the right cell and the ```QKeyEvent``` is ```space```, send your signal. – thibsc May 31 '17 at 12:12
-
@ThibautB. Yeah, I also thought about that already, but still dont know how to send the coordinate of the cell. – trangan May 31 '17 at 12:15
-
use [currentIndex()](http://doc.qt.io/qt-5/qabstractitemview.html#currentIndex), you get a ```QModelIndex```, so you have the ```row``` and the ```column```. – thibsc May 31 '17 at 12:18
2 Answers
7
Create a separate header file i.e. "customtable.h" and then in the Designer you can Promote the existing QTableWidget to this class.
class customTable:public QTableWidget
{
Q_OBJECT
public:
customTable(QWidget* parent=0):QTableWidget(parent){}
protected:
void keyPressEvent(QKeyEvent *e)
{
if(e->key()==Qt::Key_Space)
{
emit spacePressed(this->currentRow(),this->currentColumn());
}
else { QTableWidget::keyPressEvent(e); }
}
signals:
spacePressed(int r, int c);
};

lena
- 1,181
- 12
- 36
-
1thanks. I think I should add `else { QTableWidget::keyPressEvent(event);}` here. Otherwise other buttons do not work :) – trangan May 31 '17 at 14:14
-
6
You can use an event filter to do this:
class TableSpaceWatcher : public QObject {
Q_OBJECT
bool eventFilter(QObject * receiver, QEvent * event) override {
auto table = qobject_cast<QTableWidget*>(receiver);
if (table && event->type() == QEvent::KeyPress) {
auto keyEvent = static_cast<QKeyEvent*>(event);
if (keyEvent->key() == Qt::Key_Space)
emit spacePressed(table->currentRow(), table->currentColumn());
}
return false;
}
public:
using QObject::QObject;
Q_SIGNAL void spacePressed(int row, int column);
void installOn(QTableWidget * widget) {
widget->installEventFilter(this);
}
};
QTableWidget table;
TableSpaceWatcher watcher;
watcher.installOn(&table);

Kuba hasn't forgotten Monica
- 95,931
- 16
- 151
- 313