How to create a SIGNAL for QTableWidget from keyboard?

有些话、适合烂在心里 提交于 2020-12-12 06:27:32

问题


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?


回答1:


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:


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);


来源:https://stackoverflow.com/questions/44284252/how-to-create-a-signal-for-qtablewidget-from-keyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!