1、界面标题栏事件:
NonClientAreaMouseButtonPress 标题栏点击事件
NonClientAreaMouseButtonRelease 标题栏释放事件
bool CustomPopDialog::event(QEvent* event) { switch (event->type()) { case QEvent::MouseButtonRelease: //Event of mouse releasing window title case QEvent::NonClientAreaMouseButtonRelease: { QMouseEvent* e = static_cast<QMouseEvent*>(event); if (e && e->button() == Qt::LeftButton) { emit dragRelease(e->globalPos()); } m_isPress = false; if (m_timer->isActive() == true) { m_timer->stop(); } } break; case QEvent::Close: { // Signal the pop-up window to destroy emit PopDialogClose(m_pWidget); m_isPress = false; if (m_timer->isActive() == true) { m_timer->stop(); } break; } case QEvent::NonClientAreaMouseButtonPress: { QMouseEvent* e = static_cast<QMouseEvent*>(event); if (e && e->button() == Qt::LeftButton) { m_isPress = true; if (m_timer->isActive() == false) { m_timer->start(10); } } break; } case QEvent::NonClientAreaMouseMove: { QMouseEvent* e = static_cast<QMouseEvent*>(event); if (m_isPress) { int a = 0; } if (e) { emit mouseGlobalPoint(e->pos()); } break; } } return QDialog::event(event); }
2、鼠标按下事件
mousePressEvent(QMouseEvent* event)
#include <QMouseEvent> void widget::mousePressEvent(QMouseEvent* event) { //鼠标左键按下 if (event->button() == Qt::LeftButton) { //do something } //... }
3、鼠标移动事件
mouseMoveEvent(QMouseEvent* event):
pos()函数获取鼠标指针在窗口的位置,pos().x(), pos().y()获取坐标
默认是鼠标按下移动才会触发mouseMoveEvent事件,如果不想按下鼠标移动也能触发mouseMoveEvent事件可以在构造中设置鼠标跟踪:
setMouseTracking(true); //设置鼠标跟踪
如果涉及子界面的鼠标移动事件也需要在子界面的构造中加上鼠标跟踪。
setMouseTrack无效问题:
有时候子界面响应鼠标移动父界面不响应或父界面响应子界面不响应,例如:QLabel放在QStackedWidget上,QStackedWidget放在myWidget的centerWidget上,centerWidget自动放在mainWindow上(mianWindow的中心区域),myWidget继承QWidget,这时候需要层层设置:
QLabel->setMouseTrack(true);
QStackedWidget->setMouseTrack(true);
centerWidget->setMouseTrack(true);
myWidget->setMouseTrack(true);
myWidget->parentWidget()->setMouseTrack(true);
4、鼠标移入移出事件
widget中重写鼠标移入移出事件:
void enterEvent(QEvent* event); //鼠标移入界面触发 void leaveEvent(QEvent* event); //鼠标移出界面触发
5、鼠标释放事件
鼠标按下后在松开鼠标触发。
mouseReleaseEvent(QMouseEvent *event):
6、鼠标双击事件
双击鼠标触发
mouseDoubleClickEvent(QMouseEvent *event):
7、鼠标滚轮事件
event->delta()数值,角度 * 8 = delta()
//demo void THM_CT::wheelEvent(QWheelEvent * event) { // … m_currentIndex += event->delta() / 500.0; r_image=image.scaled(image.width()*currentIndex,image.height()*currentIndex,Qt::IgnoreAspectRatio, Qt::SmoothTransformation); //图片缩放 }
最后:
如果在QGraphicsView中无法触发鼠标事件,这是因为鼠标事件是被QGraphicsView里面的viewport截取了,在viewport上安装一个事件过滤器,通过事件过滤来截取鼠标事件,实现鼠标事件的透传。