# 2024.04.16

梳理按下鼠标左键并移动来绘制自由曲线的过程

* 按下鼠标左键，产生一个QMouseEvent类的指针，记作event
* QMouseEvent类继承自QEvent类，QEvent类有一个枚举值属性Type，用来表示事件的类型
* event->Type的值就是 MouseButtonPress = 2
* QMouseEvent类有一个protected的MouseButton枚举值属性b
  * 通过button()方法可以调用b的值
* event的b的值就是LeftButton = 0x00000001
* 根据event的Type的值，Qt自动判断要调用mousePressEvent()函数，并将event作为变量传递给mousePressEvent()

```cpp
void MainWindow::mousePressEvent(QMouseEvent* event)
{    
    if (event->button() == Qt::LeftButton)
        lastPoint = event->pos();
}
```

* 通过pos()方法，得到按下鼠标左键时鼠标的位置，将其存储到lastPoint中
* 在按下鼠标左键的情况下，移动鼠标，那么在下一瞬间，又产生一个新的QMouseEvent类的指针，仍记作event，这时event->Type的值就是 MouseMove = 5

```cpp
void MainWindow::mouseMoveEvent(QMouseEvent* event)
{
    if (event->buttons() & Qt::LeftButton)
    {
        endPoint = event->pos();
        update();
    }
}
```

* 通过pos()方法，获得此时鼠标的位置，将其存储到endPoint中
* 调用update()函数，进而调用paintEvent()函数

```cpp
void MainWindow::paintEvent(QPaintEvent*)
{
    QPainter pp(&pix);
    pp.drawLine(lastPoint, endPoint);
    lastPoint = endPoint;
    QPainter painter(this);
    painter.drawPixmap(0, 0, pix);
}
```

* 因为pix是个全局变量，所以在其上画的每一条线段都可以保留下来
* 将lastPoint的值更新为endPoint的值，然后开始循环往复
* 最后的最后，移动完最后一下，松开鼠标，调用

```cpp
void MainWindow::mouseReleaseEvent(QMouseEvent* event)
{
    if (event->button() == Qt::LeftButton) //鼠标左键释放    
    {
        endPoint = event->pos();
        update();
    }
}
```

* 最后lastPoint和endPoint值都是最后松开鼠标的地方


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://tysun.gitbook.io/c++/2024.04.16.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
