widget.h
#define WIDGET_H
#include <QWidget>
#include <QMouseEvent>
#include <QDebug>
#include <QKeyEvent>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = nullptr);
~Widget();
//重写鼠标事件处理函数
void mouseMoveEvent(QMouseEvent *event) override;
void mousePressEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
void mouseDoubleClickEvent(QMouseEvent *event) override;
//重写键盘事件处理函数
void keyPressEvent(QKeyEvent *event) override;
void keyReleaseEvent(QKeyEvent *event) override;
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
this->setMouseTracking(true); //设置鼠标追踪功能
}
Widget::~Widget()
{
delete ui;
}
//鼠标移动事件处理函数
void Widget::mouseMoveEvent(QMouseEvent *event)
{
if(event->buttons() == Qt::LeftButton)
{
qDebug()<<event->globalPos();
}
else if (event->buttons() == Qt::RightButton)
{
this->close();
}
else if (event->buttons() == Qt::MidButton) //按着移动鼠标
{
ui->label->move(event->pos());
}
}
//鼠标按下事件处理函数
void Widget::mousePressEvent(QMouseEvent *event)
{
//判断是哪个键被按下
if(event->button() == Qt::LeftButton)
{
ui->label->setText("鼠标左键被按下");
qDebug()<<event->pos();
}else if(event->button() == Qt::RightButton)
{
ui->label->setText("鼠标右键被按下");
qDebug()<<event->pos();
}
}
//鼠标释放事件处理函数
void Widget::mouseReleaseEvent(QMouseEvent *event)
{
//判断
if(event->button() == Qt::LeftButton)
{
ui->label->setText("鼠标左键抬起");
qDebug()<<event->pos();
}else if(event->button() == Qt::RightButton)
{
ui->label->setText("鼠标右键抬起");
qDebug()<<event->pos();
}
}
//鼠标双击事件处理函数
void Widget::mouseDoubleClickEvent(QMouseEvent *event)
{
//判断是哪个键被双击
if(event->button() == Qt::LeftButton)
{
ui->label->setText("鼠标左键被双击");
qDebug()<<event->pos();
}else if(event->button() == Qt::RightButton)
{
ui->label->setText("鼠标右键被双击");
qDebug()<<event->pos();
}
}
//键盘按下事件处理函数
void Widget::keyPressEvent(QKeyEvent *event)
{
//判断哪个键被按下了
switch(event->key())
{
case'W':
{
//判断小球是否完全脱离界面
if(ui->label->y() < 0-ui->label->height())
{
ui->label->move(ui->label->x(),this->height());
}
ui->label->move(ui->label->x(),ui->label->y()-3);
}
break;
case'S':
{
//判断小球是否完全脱离界面
if(ui->label->y() > this->height())
{
ui->label->move(ui->label->x(),0 - ui->label->height());
}
ui->label->move(ui->label->x(),ui->label->y()+3);
}
break;
case'A':
{
//判断小球是否完全脱离界面
if(ui->label->x() < 0-ui->label->width())
{
ui->label->move(this->width(),ui->label->y());
}
ui->label->move(ui->label->x()-3,ui->label->y());
}
break;
case'D':
{
//判断小球是否完全脱离界面
if(ui->label->x() > this->width())
{
ui->label->move(0-ui->label->width(),ui->label->y());
}
ui->label->move(ui->label->x()+3,ui->label->y());
}
break;
}
}
//键盘抬起事件处理函数
void Widget::keyReleaseEvent(QKeyEvent *event)
{
QString msg = QString("%1:被抬起,对应的ascii码为:%2").arg(event->text()).arg(event->key());
ui->label->setText(msg);
}
result