900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > Qt图形视图框架--图元总结

Qt图形视图框架--图元总结

时间:2018-07-01 13:35:29

相关推荐

Qt图形视图框架--图元总结

文章目录

一、基类QGraphicsItem二、内部图元2.1、椭圆图元--QGraphicsEllipseItem2.2、线段图元--QGraphicsLineItem2.3、路径图元--QGraphicsPathItem2.4、图片图元--QGraphicsPixmapItem2.5、多边形图元--QGraphicsPolygonItem2.6、矩形图元--QGraphicsRectItem2.7、简单文本路径图元--QGraphicsSimpleTextItem2.8、文本图元--QGraphicsTextItem三、附加图元3.1、SVG图元--QGraphicsSvgItem四、自定义图元

一、基类QGraphicsItem

Qt图形框架中,QGraphicsItem是图元基类;

二、内部图元

2.1、椭圆图元–QGraphicsEllipseItem

2.2、线段图元–QGraphicsLineItem

2.3、路径图元–QGraphicsPathItem

2.4、图片图元–QGraphicsPixmapItem

2.5、多边形图元–QGraphicsPolygonItem

2.6、矩形图元–QGraphicsRectItem

2.7、简单文本路径图元–QGraphicsSimpleTextItem

2.8、文本图元–QGraphicsTextItem

三、附加图元

3.1、SVG图元–QGraphicsSvgItem

QGraphicsSvgItem是用来显示SVG的图元,只需要调用:

QSvgRenderer* render = new QSvgRenderer(SVG_filePath);svgItem->setSharedRenderer(render);

四、自定义图元

所有自定义图元都必须继承图元基类QGraphicsItem或其子类;

自定义图元:添加枚举标识、重新三个虚函数

1、标识图元

每个图元都有一个枚举标识,例如路径图元的标识为:2

在场景操作中当检测Type值为2时,就可以确定这个图元是一个路径图元;

查看QGraphicsItem接口,可以发现Qt给开发者预留了标识:

开发者使用标识UserType即可,当有多个自定义图元时,可以在其上累加,例如:

class LineElementItem : public QGraphicsItem{public:enum {Type = UserType + 1};LineElementItem()~LineElementItem();}class LogicElementItem : public QGraphicsItem{public:enum {Type = UserType + 2};LogicElementItem ()~LogicElementItem ();}

2、重写虚函数int type() const【返回图元类型】

class LineElementItem : public QGraphicsItem{public:enum {Type = UserType + 1};LineElementItem()~LineElementItem();int type() const{return Type;}}

3、重写虚函数QRectF boundingRect() const【设置图元边界】

函数boundingRect()返回一个矩形,这个矩形就是自定义图元的区域(可视区域);

class LineElementItem : public QGraphicsItem{public:enum {Type = UserType + 1};LineElementItem()~LineElementItem();int type() const{return Type;}QRectF boundingRect() const//定义图元为一个128*128的矩形{qreal penwidth=1;return QRectF(0-penwidth/2,0-penwidth/2,128+penwidth,128+penwidth);}}

4、重写void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr)【绘制图元形状】

class LineElementItem : public QGraphicsItem{public:enum {Type = UserType + 1};LineElementItem()~LineElementItem();int type() const{return Type;}QRectF boundingRect() const//定义图元为一个128*128的矩形{qreal penwidth=1;return QRectF(0-penwidth/2,0-penwidth/2,128+penwidth,128+penwidth);}void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){// 选中时绘制if (option->state & QStyle::State_Selected) {painter->setPen(QPen(Qt::red, 2, Qt::DashLine));painter->setBrush(Qt::NoBrush);painter->drawRect(boundingRect().adjusted(2,2,-2,-2));}QGraphicsItem::paint(painter,option,widget);}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。