代表按键类型的枚举变量 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) //右键释放
{
...
}
}
本文详细介绍了Qt中鼠标事件的处理方式,包括如何通过QMouseEvent类的成员函数button()和buttons()来判断鼠标按键状态。文章重点讲解了不同鼠标事件(如按下、释放和移动)时这些函数的行为差异。

1万+

被折叠的 条评论
为什么被折叠?



