Qt中关于QMouseEventbuttons()和QMouseEventbutton()的使用注意

在进行QT程序开发中经常需要响应鼠标事件,在QWidget或QMainWindow的子类中可以重载如下鼠标事件实现自己需要的效果。

         virtual void

mouseDoubleClickEvent(QMouseEvent *event)

virtual void

mouseMoveEvent(QMouseEvent *event)

virtual void

mousePressEvent(QMouseEvent *event)

virtual void

mouseReleaseEvent(QMouseEvent *event)

QMouseEvent中的buttons()和button()返回按下的鼠标按键,是Qt:: MouseButton类型,包含Qt::NoButton、Qt::LeftButton、Qt:: RightButton、Qt:: MiddleButton等常见鼠标按键。

返回值为以下几种类型:

Qt::NoButton            0x00000000

Qt::LeftButton          0x00000001

Qt::RightButton        0x00000002

Qt::MidButton          0x00000004

我在mouseMoveEventmouseReleaseEvent事件中通过QMouseEvent:: button()获取鼠标按键信息,结果一直返回Qt::NoButton,非常纳闷!结果一查看Qt官方文档,针对这块有特别的解释。

        

Qt::MouseButton QMouseEvent::button() const

返回产生事件的按钮。

需要注意的是,对于鼠标移动事件,该函数返回值总是Qt::NoButton

 

Qt::MouseButtons QMouseEvent::buttons()const

返回产生事件的按钮状态,函数返回当前按下的所有按钮,按钮状态可以是Qt::LeftButton, Qt::RightButton, Qt::MidButton 或运算组合。

For mouse move events, this is all buttons that are pressed down. 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.

鼠标左键已经处在按下的状态,此时如果移动鼠标,会产生鼠标的move事件,button()返回Qt::NoButton,buttons()返回LeftButton。再按下鼠标右键,会触发鼠标的press事件,button返回RightButton,buttons()返回LeftButton | RightButton再移动鼠标,会发生move事件,button()返回Qt::NoButton,button()s返回LeftButton | RightButton再松开左键,会发生Release事件,button()返回LeftButton,buttons()返回RightButton。

简而言之,button返回“发生了此事件的按钮”,buttons返回“发生事件时还处于按下状态的按钮”。

现在就明白了,在move事件中,就需要使用buttons()来获取还处于按下状态的按钮了!

 

常用的判断条件(Event->buttons() & Qt::LeftButton)

如果鼠标左键处于按下状态,则结果为真,如果不考虑左右键都处于按下状态,则 与event->buttons() == Qt::LeftButton在结果上是相同的。

参考https://blog.csdn.net/liu_jiale1/article/details/83105226

转载于:https://www.cnblogs.com/MakeView660/p/10636126.html

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值