您的位置:首页 > 编程语言 > Qt开发

Qt鼠标事件QMouseEvent总结

2013-12-21 16:15 501 查看
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 ...

}

}

装载自:http://blog.const.net.cn/a/17083.htm
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: