//重写虚函数
QRectF boundingRect() const;//预计绘制的区域
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget /* = 0 */);//绘制
QRectF MyItem::boundingRect() const
{
qreal adjust = 0.5;
return QRectF(-100 - adjust, -100 - adjust, 200 + adjust, 200 + adjust);
}
void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
QBrush brush(QColor(200,125,125));
painter->setBrush(brush);
painter->drawRect(-100, -100, 200, 200);
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsScene scene;
scene.setSceneRect(-300, -300, 600, 600);//场景大小
scene.setItemIndexMethod(QGraphicsScene::NoIndex);//线性索引
MyItem *item = new MyItem;
scene.addItem(item);
scene.addText("Hello World!");
QGraphicsView view(&scene);
view.setRenderHint(QPainter::Antialiasing);//指定Render标签,抗锯齿
view.setCacheMode(QGraphicsView::CacheBackground);//缓存模式
view.setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);//场景重绘更新方式
view.setDragMode(QGraphicsView::ScrollHandDrag);//拖动模式,鼠标可拖动
view.resize(400, 300);
view.show();
//scene.removeItem(scene.itemAt(-10, -10, view.transform()));
return a.exec();
}
评论区