当前位置:网站首页>QT之鼠标和键盘事件重写
QT之鼠标和键盘事件重写
2022-08-03 02:29:00 【天天进步一点点】
有时候我们需要重写键盘和鼠标的事件的处理函数,那么这个时候我们就需要进行事件编程
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QMouseEvent>
#include <QWheelEvent>
#include <QKeyEvent>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
protected:
//我们来重写QT的5个标准的鼠标事件函数,从而实现我们自己想要的动作
void mouseDoubleClickEvent(QMouseEvent *event);//鼠标双击事件
void mouseMoveEvent(QMouseEvent *event);//数据表移动事件
void mousePressEvent(QMouseEvent *event);//鼠标按下事件
void mouseReleaseEvent(QMouseEvent *event);//鼠标松开事件
void wheelEvent(QWheelEvent *event); //鼠标滚轮事件
void keyPressEvent(QKeyEvent *event);//键盘事件
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
setMouseTracking(true);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::mouseDoubleClickEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton){
ui->label->setText("left button dbclicked");
}
else {
ui->label->setText("right button dbclicked");
}
}
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
QPoint pos = event->globalPos();
ui->label_2->setText(QString("(%1,%2)").arg(pos.rx()).arg(pos.ry()));
}
void MainWindow::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton){
ui->label->setText("left button pressed");
}
else {
ui->label->setText("right button pressed");
}
}
void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton){
ui->label->setText("left button released");
}
else {
ui->label->setText("right button released");
}
}
void MainWindow::wheelEvent(QWheelEvent *event)
{
if(event->delta() > 0){
ui->label_2->setText("wheel up");
}
else {
ui->label_2->setText("wheel down");
}
}
void MainWindow::keyPressEvent(QKeyEvent *event)
{
if(event->key() == Qt::Key_0)//键盘0按下
{
ui->label_2->setText("key 0 pressed");
}
if(event->key() == Qt::Key_1)
{
ui->label_2->setText("key 1 pressed");
}
}
我们来看一下运行效果
边栏推荐
猜你喜欢
随机推荐
leetcode:149. 直线上最多的点数
[Static type and dynamic type compile check and run check in Objective-C]
YYGH-BUG-06
Postman如何做接口自动化测试?
服务器在线测速系统源码
Get the first/last day of the current week, month, quarter in MySQL
Jmeter TCP/UDP测试
关于 Redis 必问面试题,你知道哪些?
numpy PIL tensor之间的相互转换
DTD约束和Schema约束
Disable the token and update the token function without awareness
实现统一账号登录,sonarqube集成ldap
常用工具链和虚拟环境-WSL
MySQL-多表查询
Excel 如何比较两列字符串是否相同?
[QNX Hypervisor 2.2用户手册]10 虚拟设备参考
46LVS+Keepalived群集
JVM internal structure and various modules operation mechanism
C语言——-动态内存开辟与管理(malloc,free,calloc,realloc)+柔性数组
数据中台建设(八):数据服务体系建设