3

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?

3
  • Try to achieve it by reimplement keyPressEvent(), when you are on the right cell and the QKeyEvent is space, send your signal.
    – thibsc
    May 31, 2017 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, 2017 at 12:15
  • use currentIndex(), you get a QModelIndex, so you have the row and the column.
    – thibsc
    May 31, 2017 at 12:18

2 Answers 2

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);
};
2
  • 1
    thanks. I think I should add else { QTableWidget::keyPressEvent(event);} here. Otherwise other buttons do not work :)
    – trangan
    May 31, 2017 at 14:14
  • @htmlamateur right, thanks, I've added an edit to my answer
    – lena
    Jun 1, 2017 at 10:03
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);

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.