#include <QApplication>
#include "mainwindow.h"
#include<QDebug>
#include<QEvent>
#include<QKeyEvent>
//先写一个类,命名为MyObeject 继承与QObjectclass
myObject:public QObject
{
public:
bool eventFilter (QObject *obj, QEvent *event) //重新实现此虚函数
{
if(event->type()==QEvent::KeyPress)
{
QKeyEvent *key=static_cast<QKeyEvent *>(event);//将QEvent类型转变为子类QKeyEvent类型,才能使用子类的key()函数
if(key->key()==Qt::Key_F1)//如果按下的键是F1
{
qDebug() << "按下了F1键"; //打印出消息,这里只是为了测试
return true;
}
}
return QObject::eventFilter(obj,event);
}
};
//在main函数调用installEventFilter()函数
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
myObject *obj= new myObject;
a.installEventFilter(obj);
MainWindow w; w.show();
return a.exec();
}
//希望可以帮助到新手