Qt drawPolyline,绘制的线段有宽度4,如何判断鼠标点击到了线上
时间: 2024-03-02 15:50:51 浏览: 39
要判断鼠标是否点击到了绘制的线段上,需要先将线段的坐标转换为屏幕坐标系下的坐标,然后通过QPainterPath类来创建一个路径,再通过QPainterPath::contains()函数来判断鼠标点击的位置是否在路径上。
具体实现步骤如下:
1. 在绘制函数中使用QPen类来设置线段的颜色和宽度,比如:
```cpp
QPen pen(Qt::black, 4);
painter.setPen(pen);
```
这里设置线段的颜色为黑色,宽度为4。
2. 在鼠标点击事件处理函数中,获取点击的位置,并将线段的坐标转换为屏幕坐标系下的坐标,比如:
```cpp
void MyWidget::mousePressEvent(QMouseEvent* event)
{
QPointF mousePos = event->pos();
QPointF lineStart = mapToGlobal(QPointF(10, 10));
QPointF lineEnd = mapToGlobal(QPointF(50, 50));
QLineF line(lineStart, lineEnd);
}
```
这里假设绘制的线段起点为(10,10),终点为(50,50),然后使用mapToGlobal()函数将线段的坐标转换为屏幕坐标系下的坐标。
3. 创建一个QPainterPath对象,并将线段添加到路径中,比如:
```cpp
QPainterPath path;
path.moveTo(lineStart);
path.lineTo(lineEnd);
```
这里使用QPainterPath::moveTo()函数将路径移动到线段的起点,然后使用QPainterPath::lineTo()函数将线段添加到路径中。
4. 调用QPainterPath::contains()函数来判断鼠标点击的位置是否在路径上,比如:
```cpp
if (path.contains(mousePos))
{
// 点击到了线段上
}
```
这里使用QPainterPath::contains()函数来判断鼠标点击的位置是否在路径上,如果返回true,则说明点击到了线段上。
注意,这里的QPainterPath对象需要在所有的绘图事件处理函数中都可见,否则无法正确绘制线段。
相关推荐
![text/x-java](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)