函数 | 区别(官方解析) |
---|
button | 返回产生事件的按钮 |
buttons | 返回产生事件的按钮状态,函数返回当前按下的所有按钮,按钮状态可以是Qt::LeftButton,Qt::RightButton,Qt::MidButton或运算组合 |
假设鼠标左键已经按下:
如果移动鼠标,会发生move事件,button返回Qt::NoButton,buttons返回LeftButton;
再按下右键,会发生press事件,button返回RightButton,buttons返回LeftButton | RightButton;
再移动鼠标,会发生move事件,button返回Qt::NoButton,buttons返回LeftButton | RightButton;
再松开左键,会发生Release事件,button返回LeftButton,buttons返回RightButton。
也就是说,button返回“发生此事件的那个按钮”,buttons返回"发生此事件时处于按下状态的那些按钮"。
常用按钮值
按钮 | 值 |
---|
NoButton | 0x00000000 |
LeftButton | 0x00000001 |
RightButton | 0x00000002 |
MidButton | 0x00000004 // ### Qt 6: remove me |
MiddleButton | MidButton |
被按下按钮 | 返回值 |
---|
左键 | 1 |
右键 | 2 |
中键 | 4 |
左 + 右 | 3 |
左 + 中 | 5 |
右 + 中 | 6 |
左 + 中 + 右 | 7 |
实例代码
判断方法 | 结果 |
---|
event->button() == Qt::LeftButton && (event->buttons() & Qt::LeftButton) | 左键按下 |
event->buttons() & Qt::LeftButton | 左键处于一直按下 |
event->button() != Qt::LeftButton && (event->buttons() & Qt::LeftButton) | 左键处于一直按下(此事件不是由左键发生) |
event->button() == Qt::LeftButton && (!(event->buttons() & Qt::LeftButton)) | 左键释放 |
event->button() == Qt::RightButton && (event->buttons() & Qt::RightButton) | 右键按下 |
event->buttons() & Qt::RightButton | 右键处于一直按下 |
event->button() != Qt::RightButton && (event->buttons() & Qt::RightButton) | 右键处于一直按下(此事件不是由右键发生) |
event->button() == Qt::RightButton && (!(event->buttons() & Qt::RightButton)) | 右键释放 |
void MyWidget::mousePressEvent(QMouseEvent *event)
{
processMouseEvent(event);
}
void MyWidget::mouseReleaseEvent(QMouseEvent *event)
{
processMouseEvent(event);
}
void MyWidget::mouseMoveEvent(QMouseEvent *event)
{
processMouseEvent(event);
}
void MyWidget::processMouseEvent(QMouseEvent * event)
{
if (event->button() == Qt::LeftButton && (event->buttons() & Qt::LeftButton))
{
}
if (event->button() != Qt::LeftButton && (event->buttons() & Qt::LeftButton))
{
}
if (event->button() == Qt::LeftButton && (!(event->buttons() & Qt::LeftButton)))
{
}
if (event->button() == Qt::RightButton && (event->buttons() & Qt::RightButton))
{
}
if (event->button() != Qt::RightButton && (event->buttons() & Qt::RightButton))
{
}
if (event->button() == Qt::RightButton && (!(event->buttons() & Qt::RightButton)))
{
}