QT开发中文网

qt QGraphicsView 绘制连续不间断的多边形

要在Qt的QGraphicsView中绘制连续不间断的多边形,可以采用以下步骤:

  1. 创建一个QGraphicsScene对象,并将其设置为QGraphicsView的场景。
  2. 创建一个QGraphicsPolygonItem对象,并将其添加到场景中。
  3. 通过调用polygon()函数获取多边形对象,并使用setPolygon()函数设置新的多边形对象。初始时,该多边形对象应为空。
  4. 在每次鼠标点击或移动时,将当前点添加到多边形对象中并更新它。可以使用QPolygonF类实现此操作。
  5. 可以使用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中绘制连续不间断的多边形。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:http://qt.0voice.com/?id=1962

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?