QGraphicsView重写paint事件实现实时画图显示

本文介绍如何在QGraphicsView中重写paint事件以实现动态画图的实时显示。通过场景类cgraphicsscene和视图类cgraphicsview的配合,以及在widget的使用中解决实时刷新时场景被白色背景覆盖的问题,确保动态绘制效果得以正确呈现。
摘要由CSDN通过智能技术生成

场景类
cgraphicsscene.h

#ifndef CGRAPHICSSCENE_H
#define CGRAPHICSSCENE_H

#include <QGraphicsScene>
#include <QGraphicsPathItem>
#include <QList>
#include "cgraphicsview.h"
class CGraphicsScene : public QGraphicsScene
{
   
    Q_OBJECT
public:
    enum Type
    {
   
        T_None,
        T_Point,
        T_Line,
        T_Circle,
        T_Ellipse,
        T_Rect,
        T_RoundRect
    };
    enum State
    {
   
        S_None,
        S_Begin,
        S_Moving,
        S_End,
    };
    CGraphicsScene(QObject *parent = 0);
public slots:
    void OnItemCreate(QPointF beginPos,QPointF endPos,int type);
private:
    QList<QGraphicsPathItem*> m_pathList;
};

#endif // CGRAPHICSSCENE_H

cgraphicsscene.cpp

#include "cgraphicsscene.h"

CGraphicsScene::CGraphicsScene(QObject *parent)
    : QGraphicsScene(parent)
{
   
    setBackgroundBrush(Qt::gray);
}

void CGraphicsScene::OnItemCreate(QPointF beginPos, QPointF endPos, int type)
{
   
    QGraphicsPathItem *item = new QGraphicsPathItem;
    item->setPen(QPen(Qt::blue,2));
    int w = endPos.x() - beginPos.x();
    int h = endPos.y() - beginPos.y();
    switch (type)
    {
   
    case T_Point:
        break;
    case T_Line:
    {
   
        QPainterPath path;
        path.moveTo(beginPos);
        path.lineTo(endPos);
        item->setPath(path);
    }
        break;
    case T_Circle:
    {
   
        QPainterPath path;
        path.addEllipse(beginPos.x(),beginPos.y(),w,h);
        item->setPath(path);
    }
        break;
    case T_Ellipse:
    {
   
        QPainterPath path;
        path.addEllipse(beginPos.x(),beginPos.y(),w,h);
        item
  • 0
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值