【QT】判断鼠标按键

本文详细介绍了Qt中鼠标事件的处理方式,包括如何通过QMouseEvent类的成员函数button()和buttons()来判断鼠标按键状态。文章重点讲解了不同鼠标事件(如按下、释放和移动)时这些函数的行为差异。

代表按键类型的枚举变量 enum Qt::MouseButton

Qt::NoButton	0x00000000
Qt::AllButtons	0x07ffffff
Qt::LeftButton	0x00000001
Qt::RightButton	0x00000002
...

通过鼠标事件获取按键
Qt::MouseButton QMouseEvent::button() const
Returns the button that caused the event.
Note that the returned value is always Qt::NoButton for mouse move events.
注意:在move事件时返回0,所以move事件无法获得按键类型

也可以通过该方法

Qt::MouseButtons QMouseEvent::buttons() const

Returns the button state when the event was generated. The button state is a combination of Qt::LeftButton, Qt::RightButton, Qt::MidButton using the OR operator.
For mouse move events, this is all buttons that are pressed down. 【move事件时返回AllButtons】
For mouse press and double click events this includes the button that caused the event.
For mouse release events this excludes the button that caused the event. 【release事件时则是按键取反,按下去那一位置零,没按下去的置一】
但实测release事件,buttons方法返回永远为0,所以还是用button方法吧

void myWidget::mousePressEvent(QMouseEvent *ev)
{
if (ev->button() & Qt::LeftButton)  //左键按下
{
...
}
if (ev->button() & Qt::RightButton)  //右键按下
{
...
}
}

void myWidget::mouseReleaseEvent(QMouseEvent *ev)
{
if (ev->button() & Qt::LeftButton)  //左键释放
{
...
}
if (ev->buttons() & Qt::RightButton)  //右键释放
{
...
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值