每个程序main ()函数的最后都会调用QApplication类的exec()函数,它会使应用程序进入事件循环,这样就可以使应用程序在运行时接收发生的各种事件。一旦有事件发生,Qt便会构建一个相应的QEvent子类的对象来表示它,然后将它传递给相应的QObject对象或者其子类对象。
举例一:
新建Qt Widget应用,项目名为myevent,基类选择QWidget,类名保持Widget不变。
第一步:
添加一个MyLineEdit类,头文件为mylineedit.h,源文件为mylineedit.cpp
mylineedit.h代码为:
#ifndef MYLINEEDIT_H
#define MYLINEEDIT_H
#include <QLineEdit>
class MyLineEdit : public QLineEdit
{
Q_OBJECT
public:
explicit MyLineEdit(QWidget * parent = nullptr);
protected:
void keyPressEvent(QKeyEvent *event) override;
};
#endif // MYLINEEDIT_H
mylineedit.cpp代码为:
#include "mylineedit.h"
#include <QKeyEvent>
#include <QDebug>
MyLineEdit::MyLineEdit(QWidget *parent)
: QLineEdit(parent)
{
}
void MyLineEdit::keyPressEvent(QKeyEvent *event)
{
qDebug() << "MyLineEdi键盘按下事件";
QLineEdit::keyPressEvent(event);
// event->ignore();
}
widget.h代码为:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
class MyLineEdit;
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget() override;
protected:
void keyPressEvent(QKeyEvent *event) override;
private:
MyLineEdit *m_lineEdit