[英]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: 所以我有以下代码描述的
QMainWindow
类型类:
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. 如您所见,该类还具有成员
DimensionDialog
和CameraControl
,它们分别是QDialog
和QWigdet
类型类。 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. 的问题是,当按下这些按钮中的一个,相应的类(
DimesionDialog
或CameraControl
)接管键事件和MainWindow
类不能捕获任何更多的关键事件。
I cannot understand why it's happening. 我不明白为什么会这样。 How do I prevent this?
我该如何预防? I want key event to be handled only by the
MainWindow
. 我希望键事件仅由
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. 这是QEvent的行为。 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). 如果您需要全局检测整个应用程序中的关键事件,则可以在重新实现的QApplication :: notify()中捕获并处理它们(有关如何使用QCoreApplication :: notify()的更多详细信息,请参见Qt文档)。
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);
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.