问题
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.
回答1:
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);
}
};
来源:https://stackoverflow.com/questions/36016069/how-to-prevent-member-qwidgets-or-qdialog-objects-taking-over-key-events-from-qm