在qt线图元中,在路径上显示出操作点,可用操作点进行拉伸,连接等,使用c++
时间: 2024-02-17 07:01:29 浏览: 25
在Qt中,可以使用QPainterPath类来创建路径,并使用QPainter类将其绘制在QWidget或QGraphicsScene等上。要在路径上显示操作点,可以使用QPainterPathStroker类来获得路径上的点,并使用QPainter类将它们绘制为操作点。
以下是一个简单的示例代码,它使用QGraphicsScene和QGraphicsPathItem类来创建一个带有操作点的路径:
```cpp
#include <QtWidgets>
class PathItem : public QGraphicsPathItem
{
public:
PathItem(QGraphicsItem *parent = nullptr)
: QGraphicsPathItem(parent)
{
setFlag(ItemIsMovable, true);
setFlag(ItemSendsGeometryChanges, true);
setPen(QPen(Qt::blue, 2.0));
setBrush(Qt::NoBrush);
}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override
{
painter->save();
// Draw the path
painter->setPen(pen());
painter->setBrush(brush());
painter->drawPath(path());
// Draw the control points
painter->setPen(QPen(Qt::black, 1.0));
painter->setBrush(Qt::white);
painter->drawPath(controlPointsPath());
painter->restore();
}
QVariant itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value) override
{
if (change == ItemPositionHasChanged) {
updateControlPointsPath();
}
return QGraphicsItem::itemChange(change, value);
}
private:
QPainterPath controlPointsPath() const
{
QPainterPath path;
const qreal radius = 4.0;
foreach (const QPointF &point, controlPoints()) {
path.addEllipse(QRectF(point - QPointF(radius, radius), QSizeF(radius * 2.0, radius * 2.0)));
}
return path;
}
QVector<QPointF> controlPoints() const
{
QVector<QPointF> points;
QPainterPathStroker stroker;
stroker.setWidth(10.0);
stroker.setCapStyle(Qt::RoundCap);
stroker.setJoinStyle(Qt::RoundJoin);
QPainterPath strokePath = stroker.createStroke(path());
for (int i = 0; i < strokePath.elementCount(); ++i) {
const QPainterPath::Element &element = strokePath.elementAt(i);
if (element.type == QPainterPath::CurveToElement) {
points << element.value;
}
}
return points;
}
void updateControlPointsPath()
{
prepareGeometryChange();
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QGraphicsScene scene;
QGraphicsView view(&scene);
view.setRenderHint(QPainter::Antialiasing);
view.setSceneRect(-200, -200, 400, 400);
PathItem *pathItem = new PathItem;
QPainterPath path;
path.moveTo(-100, -100);
path.lineTo(100, -100);
path.cubicTo(100, 100, -100, 100, -100, -100);
pathItem->setPath(path);
scene.addItem(pathItem);
view.show();
return app.exec();
}
```
在这个例子中,PathItem类继承自QGraphicsPathItem,并重写了paint()和itemChange()方法。paint()方法用于绘制路径和操作点,itemChange()方法用于在项的位置发生更改时更新操作点的位置。controlPoints()方法使用QPainterPathStroker类在路径上获取操作点的位置,updateControlPointsPath()方法用于在需要重新计算操作点位置时调用。
在main()函数中,我们创建了一个QGraphicsScene和一个QGraphicsView,然后创建了一个PathItem对象,并将其添加到场景中。我们设置了路径,并使用setPath()方法将其设置为PathItem的路径。最后,我们显示了QGraphicsView并运行了应用程序。
运行这个例子,你会看到一个带有操作点的路径。你可以使用鼠标拖动PathItem对象,并使用操作点进行拉伸和连接。