简体   繁体   中英

How to prevent member QWidgets or QDialog objects taking over key events from QMainWindow once the dialog has been clicked by the mouse?

So I have QMainWindow type class which described by the following code:

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    void closeEvent(QCloseEvent *);\
    DimensionDialog *newResolution;
    Ui::MainWindow *ui;
    ImageInteraction *liveVideo;
    ImageInteraction *modifiedVideo;
    CameraControl *cameraControl;
    QPushButton *pushToTalk;
    QPushButton *audioSettingsSetup;
    AudioSettings *audioSettings;
    QPushButton *numberOfRunningThreads;

protected:
    void keyPressEvent(QKeyEvent * event);
    void keyReleaseEvent(QKeyEvent * event);

private slots:
    void restartVideoWithNewResolution(int, int);
};

From there you can see that this class does handle some key events.

As you can see, this class also has members DimensionDialog and CameraControl , which are respectively QDialog and QWigdet type classes. Now, these two members have their own slots as well, which are called when certain buttons are pressed. The problem is that when one of these buttons are pressed, the corresponding class (either DimesionDialog or CameraControl ) takes over the key events and the MainWindow class cannot catch any more of the key events.

I cannot understand why it's happening. How do I prevent this? I want key event to be handled only by the MainWindow .

Thanks.

If you want to propagate key event to parent you should ignore it explicitly.

void DimensionDialog:keyPressEvent(QKeyEvent *event)
{
    // ...
    // do something then propagate event to parent
    event->ignore();
}

It is QEvent's behaviour. So, for mouse events it should work as well.

If you need to detect key events globally in the whole application then you can catch and process them in reimplemented QApplication::notify() (for more details how to use QCoreApplication::notify() see Qt docs on that).

class KeyEventAwareApp : public QApplication
{
  public:
    using QApplication::QApplication;

    bool notify(QObject* object,QEvent* event)
    {
      if(event->type() == QEvent::KeyPress)
      {
        // do any event processing here, for example redirect it to other object
        // if swallow event then
        return true;
        // otherwise send event to the receiver
        return object->event(event);
      }
      // we are interested only in key events, so forward the rest to receivers
        return object->event(event);
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM