Head file
#ifndef FIRSTEVENT_H
#define FIRSTEVENT_H
#include <QMainWindow>
#include <QMouseEvent>
#include <QKeyEvent>
#include <QEvent>
namespace Ui {
class FirstEvent;
}
class FirstEvent : public QMainWindow
{
Q_OBJECT
public:
explicit FirstEvent(QWidget *parent = 0);
~FirstEvent();
//鼠标事件
void mousePressEvent(QMouseEvent *);
void mouseReleaseEvent(QMouseEvent *);
void mouseMoveEvent(QMouseEvent* e);
//键盘事件
void keyPressEvent(QKeyEvent *evt);
//evnet
bool event(QEvent *event);
private:
Ui::FirstEvent *ui;
};
#endif // FIRSTEVENT_H
CPP file
#include "firstevent.h"
#include "ui_firstevent.h"
#include <QDebug>
FirstEvent::FirstEvent(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::FirstEvent)
{
ui->setupUi(this);
}
FirstEvent::~FirstEvent()
{
delete ui;
}
void FirstEvent::mousePressEvent(QMouseEvent *)
{
qDebug()<<"鼠标按下";
}
void FirstEvent::mouseReleaseEvent(QMouseEvent *)
{
qDebug()<<"鼠标释放";
}
void FirstEvent::mouseMoveEvent(QMouseEvent *e)
{
ui->label->move(e->pos());
}
void FirstEvent::keyPressEvent(QKeyEvent *evt)
{
int key = evt->key();//键盘键值
qDebug()<<key;
int x = ui->label->x();
int y = ui->label->y();
switch (key) {
case Qt::Key_A:
case Qt::Key_Left:
ui->label->move(x-10,y);
break;
case Qt::Key_D:
case Qt::Key_Right:
ui->label->move(x+10,y);
break;
case Qt::Key_W:
case Qt::Key_Up:
ui->label->move(x,y-10);
break;
case Qt::Key_S:
case Qt::Key_Down:
ui->label->move(x,y+10);
break;
default:
break;
}
}
bool FirstEvent::event(QEvent *event)
{
static int i=0;
//qDebug()<<"******************"<<i++;
return QMainWindow::event(event);
}
References
Qt5鼠标和键盘事件的简单示例 http://www.echojb.com/qt/2017/12/25/473349.html