一、前言
本文介绍鼠标位置坐标获取,控制鼠标位置前文有文章写了。
二、环境
qt5.7 win8
三、正文
获取鼠标状态应用到几个函数
1移动mouseMoveEvent
2点击mousePressEvent
3释放mouseReleaseEvent
4双击mouseDoubleClickEvent
5滚轮wheelEvent
下面就通过程序说明一下每个函数怎么使用
//移动
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
QPoint p_ab = event->globalPos();//整个桌面位置
QPoint p_re = event->pos();//窗口内位置
QString str;
str = QString("%1 , %2").arg(p_ab.x()).arg(p_ab.y());
ui->lineEdit4_2->setText(str);
//str = QString("%1 , %2").arg(p_re.x()).arg(p_re.y());
//ui->lineEdit4_3->setText(str);
}
//点击
void MainWindow::mousePressEvent(QMouseEvent *event)
{
//获得鼠标的x , y 坐标 event->x , event->y
//判断点击的是左键还是右键 event->button()==Qt::LeftButton(Qt::RightButton)
qDebug()<<event->globalPos();
qDebug()<<event->globalX();
qDebug()<<event->globalY();
ui->lineEdit4_3->setText(QString("%1 , %2").arg(event->globalX()).arg(event->globalY()));
}
//释放
void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
qDebug()<<event->globalX();
qDebug()<<event->globalY();
//nowmouseplace(event->globalX(),event->globalY());
}
//双击
void MainWindow::mouseDoubleClickEvent(QMouseEvent *event)
{
// 如果是鼠标左键按下
if (event->button() == Qt::LeftButton){
qDebug() << "left double click";
}
else if (event->button() == Qt::RightButton){
qDebug() << "right double click";
}
}
//滚轮
void MainWindow::wheelEvent(QWheelEvent *event)
{
int wheel_val = event->delta();
//当滚轮远离使用者时
if (wheel_val > 0){
qDebug() << "wheel forward: " << wheel_val;
}
else{//当滚轮向使用者方向旋转时
qDebug() << "wheel backward: " << wheel_val;
}
}
如果想要获取窗口外某一点的鼠标坐标,可以通过在窗口内点击鼠标左键,然后按住左键拖到想要知道坐标的位置,在松开左键,然后就会进入到鼠标释放函数,在处理相应的坐标位置数据即可。
还有一种方式是,先将聚焦在本窗口,然后鼠标移动到想要知道坐标的位置,不点击,然后用一下函数方法,就是通过按键来实现获取位置
void MainWindow::keyPressEvent(QKeyEvent *event)
{
int keyValue = event->key();
if (keyValue == Qt::Key_Control)
{//获取鼠标位置
qDebug() << "=== press key";
QPoint pt = QCursor::pos();//获取鼠标的绝对位置
QString str;
str = QString("%1 , %2").arg(pt.x()).arg(pt.y());
ui->lineEdit4_2->setText(str);//显示
// nowmouseplace(pt.x(),pt.y());
}
}
四、结语
有了这篇文章和前文,鼠标的操作和获取状态都知道如何使用了。