QgsGeometry没有fromPolygon成员
时间: 2024-04-19 18:29:56 浏览: 8
非常抱歉,我之前的回答有误。在QGIS中,确实没有`fromPolygon`方法来直接将`QPolygonF`转换为`QgsGeometry`。感谢您的指出。
要创建一个矩形的`QgsGeometry`对象,您可以使用`QgsGeometry::fromRect`方法。以下是一个修正后的示例:
```cpp
void YourMapTool::mousePressEvent(QMouseEvent* event)
{
if (event->button() == Qt::LeftButton)
{
// 获取鼠标按下的坐标点
QPoint centerPoint = event->pos();
// 计算矩形的四个角点
double width = 30.0; // 矩形宽度
double height = 30.0; // 矩形高度
double angle = m_dAngle; // 旋转角度(顺时针)
double halfWidth = width / 2;
double halfHeight = height / 2;
QPointF topLeft(-halfWidth, halfHeight);
QPointF topRight(halfWidth, halfHeight);
QPointF bottomRight(halfWidth, -halfHeight);
QPointF bottomLeft(-halfWidth, -halfHeight);
// 根据旋转角度对矩形进行旋转
QMatrix matrix;
matrix.rotate(angle);
topLeft = matrix.map(topLeft);
topRight = matrix.map(topRight);
bottomRight = matrix.map(bottomRight);
bottomLeft = matrix.map(bottomLeft);
// 构造QPolygonF对象,表示矩形的四个角点
QPolygonF polygon;
polygon << centerPoint + topLeft << centerPoint + topRight
<< centerPoint + bottomRight << centerPoint + bottomLeft;
// 构造QgsGeometry对象,表示矩形
QgsGeometry geometry;
geometry.fromRect(QRectF(polygon.boundingRect()));
// 绘制矩形
m_pRubBand->setToGeometry(geometry, nullptr);
m_pRubBand->setColor(QColor(255, 0, 0)); // 设置矩形的颜色
m_pRubBand->setWidth(2); // 设置矩形的线宽
// 在地图上显示矩形
QgsMapCanvas* canvas = QgsMapTool::canvas();
canvas->refresh();
}
QgsMapTool::mousePressEvent(event);
}
```
请注意,我们使用`QPolygonF`的`boundingRect`方法来获取矩形的边界框,并将其传递给`fromRect`方法来创建`QgsGeometry`对象。
非常抱歉给您带来了困惑,希望这次能够解决您的问题。如果您还有其他问题,请随时提问。