Qt鼠标事件QMouseEvent总结

来源:互联网 发布:ol3vs数据库app最新版 编辑:程序博客网 时间:2024/06/07 01:44

转自[喝小酒的网摘]http://blog.hehehehehe.cn/a/17083.htm

/*---------------------------------------------------------------------------------------------------------*/

1、QMouseEvent中的坐标

QMouseEvent中保存了两个坐标,一个是全局坐标,当然另外一个是局部坐标。
全局坐标(globalPos())即是桌面屏幕坐标(screen coordinates),这个跟windows下的调用getCursorPos函数得到的结果一致。
局部坐标(pos())即是相对当前active widget的坐标,左上角坐标为(0, 0)。

补充一个公式:
this->mapFromGlobal(this->cursor().pos()) = event.pos()

2、鼠标跟踪
在qt中,鼠标跟踪对应函数mouseMoveEvent。但是,默认情况下他并不能如期象你想象的那样响应鼠标的移动。此时,你只需在合适的位置调用一下函数setMouseTracking(true)即可。
If mouse tracking is switched off, mouse move events only occur if a mouse button is pressed while the mouse is being moved. 
If mouse tracking is switched on, mouse move events occur even if no mouse button is pressed.
默认情况下,mouseMoveEvent响应你按下鼠标的某个键(拖动,但不局限于左键拖动)的鼠标移动。

3、鼠标左键拖动和左键点击的判断
鼠标左键点击很容易判断,一般就是在重写mousePressEvent函数,示例如下:
void XXXWidget::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
       // todo ...
}
}
左键拖动的判断一般放在mouseMoveEvent函数中,但是你不能向上例一样来判断,因为该函数的event参数总是返回Qt::NoButton。你可以这样做:
void XXXWidget::mouseMoveEvent(QMouseEvent *event)
{
if(event->buttons() & Qt::LeftButton)
{
       // todo ...
}

}

0 0
原创粉丝点击