鼠标事件分为四种:
1.按下
2.抬起
3.移动
4.双击
鼠标事件继承与QWidget
void mouseDoubleClickEvent(QMouseEvent *event) void mouseMoveEvent(QMouseEvent *event) void mousePressEvent(QMouseEvent *event) void mouseReleaseEvent(QMouseEvent *event)
重写这四个函数,就能够让自定义控件支持鼠标操作。
QT中用QMouseEvent类来表达一个鼠标事件
x,y :坐标
globleX,globleY:全局坐标
buttun:鼠标的按键
例子: 当鼠标按下的时候,画出鼠标移动的轨迹,直到松开
(1)按下时
m_pressFlag=true;
(2)移动时
记录轨迹
(3)松开时
m_pressFlag=false;
circlewidget.h
#ifndef CIRCLAWIDGET_H #define CIRCLAWIDGET_H #include <QFrame> #include<QVector> #include<QMouseEvent> class CircleWidget:public QFrame { Q_OBJECT public: CircleWidget(QWidget *parent); ~CircleWidget(); private: void paintEvent(QPaintEvent *event); void mouseDoubleClickEvent(QMouseEvent *event); void mouseMoveEvent(QMouseEvent *event); void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); private: bool m_pressFlag; QVector<QPoint>m_points; }; #endif // CIRCLAWIDGET_H
circlewidget.cpp
# include"circlewidget.h" #include<QPainter> #include<QDebug> CircleWidget::CircleWidget(QWidget *parent):QFrame(parent) { m_pressFlag=false; } CircleWidget::~CircleWidget() { } void CircleWidget::paintEvent(QPaintEvent *event) { QPainter painter(this); int width=this->width(); int height=this->height(); painter.setBrush(QColor(0,0,0)); painter.drawRect(0,0,width,height); QPen pen(QColor(0xFF,0,0)); painter.setPen(pen); if(m_pressFlag) { for(int i=0;i<m_points.size()-1;i++) { QPoint & p1=m_points[i]; QPoint & p2=m_points[i+1]; painter.drawLine(p1,p2); } } } void CircleWidget::mouseDoubleClickEvent(QMouseEvent *event) { } void CircleWidget::mouseMoveEvent(QMouseEvent *event) { if(m_pressFlag) { QPoint pos=event->pos(); m_points.append(pos); qDebug("(%d,%d)",pos.x(),pos.y()); update(); } } void CircleWidget::mousePressEvent(QMouseEvent *event) { m_pressFlag=true; } void CircleWidget::mouseReleaseEvent(QMouseEvent *event) { m_pressFlag=false; }
结果:
#include"circlewidget.h"
#include<QPainter>
#include<QDebug>
CircleWidget::CircleWidget(QWidget*parent):QFrame(parent)
{
m_pressFlag=false;
}
CircleWidget::~CircleWidget()
{
}
voidCircleWidget::paintEvent(QPaintEvent*event)
{
QPainterpainter(this);
intwidth=this->width();
intheight=this->height();
painter.setBrush(QColor(0,0,0));
painter.drawRect(0,0,width,height);
QPenpen(QColor(0xFF,0,0));
painter.setPen(pen);
if(m_pressFlag)
{
for(inti=0;i<m_points.size()-1;i++)
{
QPoint&p1=m_points[i];
QPoint&p2=m_points[i+1];
painter.drawLine(p1,p2);
}
}
}
voidCircleWidget::mouseDoubleClickEvent(QMouseEvent*event)
{
}
voidCircleWidget::mouseMoveEvent(QMouseEvent*event)
{
if(m_pressFlag)
{
QPointpos=event->pos();
m_points.append(pos);
qDebug("(%d,%d)",pos.x(),pos.y());
update();
}
}
voidCircleWidget::mousePressEvent(QMouseEvent*event)
{
m_pressFlag=true;
}
voidCircleWidget::mouseReleaseEvent(QMouseEvent*event)
{
m_pressFlag=false;
}