1

I want to handle keypress event for all the child widgets, for which I am trying something like below:

Widget::Widget(QWidget *parent):QWidget(parent)
{
    QGroupBox *gBox = new QGroupBox(this);

    QPushButton *button1 = new QPushButton("1");
    QPushButton *button2 = new QPushButton("2");

    QVBoxLayout *vBox = new QVBoxLayout;
    vBox->addWidget(button1);
    vBox->addWidget(button2);
    gBox->setLayout(vBox);

    gBox->installEventFilter(this);
    button1->installEventFilter(this);
    button2->installEventFilter(this);
}

bool Widget::eventFilter(QObject *obj, QEvent *event)
{ 
if (event->type() == QEvent::KeyPress)
{
    if(obj == gBox)
    {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        if(keyEvent->key() == Qt::Key_F1)
        {
            emit somesignal();
        }
    }
   if(obj == button1)
   {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        if(keyEvent->key() == Qt::Key_F1)
        {
            emit somesignal1();
        }
   }
   if(obj == button2)
   {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        if(keyEvent->key() == Qt::Key_F1)
        {
            emit somesignal2();
        }
    }
}
return QObject::eventFilter(obj, event);
}

But whwnever I press F1, only somesignal() is emitted. I want to emit somesignal1(), somesignal2() also, for button1 and button2.

Can somebody help me to achieve this?

mtb
  • 1,350
  • 16
  • 32
Nikhil Singh
  • 81
  • 10

1 Answers1

0

You should implement a window-global QShortcut, and use qApp->focusWidget() to determine which widget you want help on. You should use the property framework to set the help URL for a widget:

const char kHelpUrl = "helpUrl";

void setHelpUrl(QWidget * w, const QUrl & url) {
  w->setProperty(kHelpUrl, url);
}
QUrl getFocusedHelpUrl() {
  auto w = qApp->focusWidget();
  return w ? w->property(kHelpURL).value<QUrl>() : QUrl{};
}

void showHelp() {
  auto url = getFocusedHelpUrl();
  ...
}

class MainWin : public QDialog {
  ...
  QPushButton button1{"Hello"};
  QPushButton button2{"GoodBye"};
public:
  MainWin(QWidget * parent = nullptr) : QDialog{parent}
  {
    setHelpUrl(&button1, {"qthelp://button1"});
    setHelpUrl(&button2, {"qthelp://button2"});
    ...
  }
};

int main(int argc, char ** argv) {
  QApplication app{argc, argv};
  ...
  MainWindow mainWin;
  QShortcut s{QKeySequence::HelpContents, &mainWin};
  QObject::connect(&s, &QShortcut::activated, showHelp);
  ...
  return app.exec();
}
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313