Qt 鼠标事件

鼠标事件

鼠标事件包括鼠标左键点击,右键点击,双击,滚动滚轮等。我们先创建一个QApplication项目,类名字为Widget,基类选择QWidget。在widget.ui里添加一个QTextEdit, 依次实现这些功能。

鼠标按下与移动

先在Widget的构造函数中,我们先给鼠标设置一个小手的样式

1
2
3
4
5
6
7
8
9
10
11
12
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
//创建光标对象
QCursor cursor;
//修改鼠标形状
cursor.setShape(Qt::OpenHandCursor);
//设置鼠标
setCursor(cursor);
}

我们将鼠标设置为打开的手的形象。
我们在鼠标左键按下时,获取鼠标和窗口左上角的位置偏移量,并且设置光标为CloseHandCursor形象。
鼠标右键按下时,设置为别的资源图标

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void Widget::mousePressEvent(QMouseEvent *event)
{
//如果是鼠标左键按下
if(event->button() == Qt::LeftButton){
QCursor cursor;
cursor.setShape(Qt::ClosedHandCursor);
QApplication::setOverrideCursor(cursor);
offset = event->globalPos() - pos();

}else if(event->button() == Qt::RightButton){
QCursor cursor(QPixmap(":/res/mouse.png"));
QApplication::setOverrideCursor(cursor);
}
}

然后我们实现释放事件,在释放鼠标时,将鼠标恢复为原来的OpenHandCursor形象

1
2
3
4
5
void Widget::mouseReleaseEvent(QMouseEvent *event)
{
//释放事件
QApplication::restoreOverrideCursor();
}

双击实现窗口放大

我们通过实现双击左键,让窗口最大化,如果已经最大化,则让窗口再变回正常模式。

1
2
3
4
5
6
7
8
9
10
void Widget::mouseDoubleClickEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton){
if(windowState() != Qt::WindowFullScreen){
setWindowState(Qt::WindowFullScreen);
}else{
setWindowState(Qt::WindowNoState);
}
}
}

拖动鼠标移动窗口

因为之前我们在鼠标左键点击后保存了窗口和鼠标的偏移量,我们可以在鼠标移动的过程中,根据偏移量和鼠标的位置,重设窗口的位置,进而实现窗口随着鼠标拖动而移动的效果。

1
2
3
4
5
6
7
8
9
void Widget::mouseMoveEvent(QMouseEvent *event)
{
//移动过程中判断鼠标是左键点击并且移动,那么要用buttons,返回的是鼠标状态的集合
if(event->buttons() & Qt::LeftButton){
//获取窗口应当移动到的位置
QPoint windowpos = event->globalPos() - offset;
this->move(windowpos);
}
}

滚轮事件

我们可以在Widget里添加textEdit,然后在鼠标滚轮滚动的时候,根据滚轮的方向缩放textEdit的文字.

1
2
3
4
5
6
7
8
9
10
11
void Widget::wheelEvent(QWheelEvent *event)
{
//鼠标滚动远离使用者放大textedit
if(event->delta() > 0){
qDebug() << "catch wheel event delta > 0" << endl;
ui->textEdit->zoomIn();
}else {
qDebug() << "catch wheel event delta < 0" << endl;
ui->textEdit->zoomOut();
}
}

在鼠标滚轮向前滚动的时候delta大于0,是放大textEdit,向后滚动的时候delta小于0,是缩小textEdit.

总结

源码连接:
https://gitee.com/secondtonone1/qt-learning-notes