网站备案授权书模板,龙岗网站制作市场,网站seo工作,建网站的步骤是哪些【QT学习】Graphics View框架#xff08;进阶篇#xff09;- 派生QGraphicsItem类创建自定义图元item-CSDN博客
前言
本篇#xff0c;我们将通过对QGraphicsItem类进行派生#xff0c;创建自定义图元item并显示在窗口中。我们将以创建一张从文件读取的图片item为例进行分…【QT学习】Graphics View框架进阶篇- 派生QGraphicsItem类创建自定义图元item-CSDN博客
前言
本篇我们将通过对QGraphicsItem类进行派生创建自定义图元item并显示在窗口中。我们将以创建一张从文件读取的图片item为例进行分析。
一、实现效果 二、实现流程
1.创建继承基类QGraphicsItem的派生类myItem 2.重新配置生成的头文件
1在类中添加头文件QGraphicsItem 2重写生成的customItem类 3重写后的customItem类 重写customItem类使其继承QObject类这样才能在该类中使用connect函数连接信号和槽。
4重新执行qmake重要重要重要否则编译会报错error: undefined reference to vtable for 3.在类中使用QPixmap创建图片对象并加载 4.重写基类QGraphicsItem的两个纯虚函数 纯虚函数QRectF boundingRect() const自定义图元边界计算图元轮廓的垂直边界最小矩形。纯虚函数void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget Q_NULLPTR)绘制需要显示的图像。在该实例中我们需要对加载后的图片进行绘制。
5.在main函数中定义并显示自定义图元 三、完整源码
1.main.cpp文件
#include widget.h
#include QApplication#include QGraphicsItem //图元
#include QGraphicsScene //场景
#include QGraphicsView //视图
#include customItem.hint main(int argc, char *argv[])
{QApplication a(argc, argv);//创建视图QGraphicsView *view new QGraphicsView();//创建场景QGraphicsScene *scene new QGraphicsScene();//创建自定义图元项customItem *item new customItem();//将场景添加到视图中view-setScene(scene);//将图元添加到场景中scene-addItem(item);//设置窗口大小view-resize(350,350);//窗口显示view-show();return a.exec();
}2.customItem.h文件
#ifndef CUSTOMITEM_H
#define CUSTOMITEM_H#include QGraphicsItem
#include QPixmapclass customItem : public QObject,public QGraphicsItem
{Q_OBJECT
public:customItem();QPixmap picture;QRectF boundingRect() const;void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget Q_NULLPTR);virtual ~customItem(){}
};#endif // CUSTOMITEM_H3.customItem.cpp文件
#include QPainter
#include customitem.hcustomItem::customItem()
{this-picture.load(./picture/search.png);
}QRectF customItem::boundingRect() const
{return QRectF(0,0,this-picture.width(),this-picture.height());
}void customItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{painter-drawPixmap(0,0,this-picture);
}总结
以上就是Graphics View框架进阶篇- 派生QGraphicsItem类创建自定义图元item的所有内容。