//头文件
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QMouseEvent>//鼠标处理事件
#include <QKeyEvent>//键盘处理事件
#include <QDebug>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
void keyPressEvent(QKeyEvent *event);
void keyReleaseEvent(QKeyEvent *event);
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void mouseDoubleClickEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
//主函数测试
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
//.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::keyPressEvent(QKeyEvent *event)
{
QString msg;
msg=event->text()+" was pressed ascii->"+QString::number(event->key());
ui->label1->setText(msg);
}
//键盘抬起处理事件函数的定义
void Widget::keyReleaseEvent(QKeyEvent *event)
{
QString msg;
msg=event->text()+" was released ascii->"+QString::number(event->key());
ui->label2->setText(msg);
}
//鼠标按下处理事件函数的定义
void Widget::mousePressEvent(QMouseEvent *event)
{
if(event->buttons()==Qt::LeftButton)
{
ui->label3->setText("mouse left pressed");
}
else if(event->buttons()==Qt::RightButton)
{
ui->label3->setText("mouse right pressed");
}
else if(event->buttons()==Qt::MidButton)
{
ui->label3->setText("mouse mid pressed");
}
}
//鼠标抬起处理事件函数的定义
void Widget::mouseReleaseEvent(QMouseEvent *event)
{
if(event->button()==Qt::LeftButton)
{
ui->label4->setText("mouse left released");
}
else if(event->button()==Qt::RightButton)
{
ui->label4->setText("mouse right released");
}
else if(event->button()==Qt::MidButton)
{
ui->label4->setText("mouse mid released");
}
}
//鼠标双击处理事件函数的定义
void Widget::mouseDoubleClickEvent(QMouseEvent *event)
{
if(event->buttons()==Qt::LeftButton)
{
if(event->buttons()==Qt::LeftButton)
{
ui->label5->setText("left double click");
}
}
else if(event->buttons()==Qt::RightButton)
{
if(event->buttons()==Qt::RightButton)
{
ui->label5->setText("right double click");
}
}
else if(event->buttons()==Qt::MidButton)
{
if(event->buttons()==Qt::MidButton)
{
ui->label5->setText("mid double click");
}
}
}
void Widget::mouseMoveEvent(QMouseEvent *event)
{
QString str=QString("x=%1,y=%2").arg(event->x()).arg(event->y());
ui->label6->setText(str);
}