QT开发中文网

qt QGraphicsView 在场景图层中绘制连续不间断的多边形

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

  1. 创建一个自定义QGraphicsItem,用于表示多边形。
  2. 实现该自定义QGraphicsItem的paint()函数,在其中绘制多边形。
  3. 在QGraphicsView上注册鼠标事件(mousePressEvent, mouseMoveEvent和mouseReleaseEvent),以便捕获用户的鼠标操作。
  4. 根据鼠标事件更新多边形,并将其添加到场景中。

下面是一个示例代码,演示如何实现这个功能:

#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QMouseEvent>

class PolygonItem : public QGraphicsItem
{
public:
    PolygonItem(QGraphicsItem *parent = nullptr)
        : QGraphicsItem(parent), pen_(Qt::black), brush_(Qt::NoBrush) {}

    QRectF boundingRect() const override
    {
        return polygon_.boundingRect();
    }

    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
    {
        painter->setPen(pen_);
        painter->setBrush(brush_);
        painter->drawPolygon(polygon_);
    }

    void addPoint(const QPointF& point)
    {
        if (polygon_.size() == 0 || polygon_.last() != point) // 只有当当前点和上一个点不同时才添加
        {
            polygon_ << point;
            update(); // 刷新画布
        }
    }

private:
    QPolygonF polygon_;
    QPen pen_;
    QBrush brush_;
};

class GraphicsView : public QGraphicsView
{
public:
    GraphicsView(QWidget *parent = nullptr)
        : QGraphicsView(parent)
    {
        scene_ = new QGraphicsScene(this);
        setScene(scene_);
        
        polygon_ = new PolygonItem();
        scene_->addItem(polygon_);

        // 设置画布大小为500x500
        setFixedSize(500, 500);

    }

protected:
    void mousePressEvent(QMouseEvent *event) override
    {
        if (event->button() == Qt::LeftButton)
            polygon_->addPoint(mapToScene(event->pos()));
    }

    void mouseMoveEvent(QMouseEvent *event) override
    {
        if (event->buttons() & Qt::LeftButton)
            polygon_->addPoint(mapToScene(event->pos()));
    }

private:
    QGraphicsScene* scene_;
    PolygonItem* polygon_;
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    GraphicsView view;
    view.show();

    return a.exec();
}

在这个例子中,我们创建了一个名为PolygonItem的自定义QGraphicsItem,用于表示多边形。我们实现了该自定义QGraphicsItem的paint()函数,在其中绘制多边形。然后在QGraphicsView上注册鼠标事件(mousePressEvent, mouseMoveEvent和mouseReleaseEvent),以便捕获用户的鼠标操作。当用户单击或移动鼠标时,我们根据当前鼠标位置更新多边形,并将其添加到场景中。

希望这个例子能够帮助你解决问题。

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?