要在Qt的QGraphicsView中绘制连续不间断的多边形,可以采用以下步骤:
- 创建一个QGraphicsScene对象,并将其设置为QGraphicsView的场景。
- 创建一个QGraphicsPolygonItem对象,并将其添加到场景中。
- 通过调用polygon()函数获取多边形对象,并使用setPolygon()函数设置新的多边形对象。初始时,该多边形对象应为空。
- 在每次鼠标点击或移动时,将当前点添加到多边形对象中并更新它。可以使用QPolygonF类实现此操作。
- 可以使用setPen()和setBrush()函数设置线条和填充颜色。
下面是一个示例代码:
#include <QtWidgets/QApplication>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QGraphicsScene>
#include <QtWidgets/QGraphicsView>
#include <QtGui/QMouseEvent>
class PolygonItem : public QGraphicsPolygonItem
{
public:
PolygonItem(QGraphicsItem *parent = nullptr)
: QGraphicsPolygonItem(parent)
{
setPen(QPen(Qt::black, 2));
setBrush(Qt::NoBrush);
}
void addPoint(const QPointF& point)
{
QPolygonF polygon = this->polygon();
polygon << point;
setPolygon(polygon);
}
};
class GraphicsView : public QGraphicsView
{
public:
GraphicsView(QWidget *parent = nullptr)
: QGraphicsView(parent)
{
scene_ = new QGraphicsScene(this);
setScene(scene_);
polygon_ = new PolygonItem();
scene_->addItem(polygon_);
}
protected:
void mousePressEvent(QMouseEvent *event) override
{
if (event->button() == Qt::LeftButton)
{
QPointF point = mapToScene(event->pos());
polygon_->addPoint(point);
}
}
void mouseMoveEvent(QMouseEvent *event) override
{
if (event->buttons() & Qt::LeftButton)
{
QPointF point = mapToScene(event->pos());
polygon_->addPoint(point);
}
}
private:
QGraphicsScene* scene_;
PolygonItem* polygon_;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QMainWindow mainWindow;
GraphicsView view(&mainWindow);
// 显示视图和主窗口
mainWindow.setCentralWidget(&view);
mainWindow.show();
return a.exec();
}
在这个例子中,我们创建了一个自定义的QGraphicsPolygonItem对象,并将其添加到场景中。我们还重写了mousePressEvent()和mouseMoveEvent()函数,在每次鼠标点击或移动时向多边形对象中添加当前点。最后,我们将生成的图像显示在Qt的QGraphicsView中。
希望这个例子能够帮助你在Qt的QGraphicsView中绘制连续不间断的多边形。