在 Qt 的 QGraphicsView 中,可以使用 QGraphicsScene 来管理和展示图形项。如果要添加数量不定的图形项,可以通过 QGraphicsScene 提供的 addItem() 函数来实现。具体步骤如下:

  1. 创建 QGraphicsScene 对象。
QGraphicsScene *scene = new QGraphicsScene(this);
  1. 创建图形项,并添加到 QGraphicsScene 中。
QGraphicsEllipseItem *item1 = new QGraphicsEllipseItem(0, 0, 50, 50);
QGraphicsRectItem *item2 = new QGraphicsRectItem(0, 0, 50, 50);
scene->addItem(item1);
scene->addItem(item2);
  1. 将 QGraphicsScene 设置为 QGraphicsView 的场景。
ui->graphicsView->setScene(scene);
  1. 如果要移动图形项,可以通过 QGraphicsItem 提供的 setPos() 函数来实现。
item1->setPos(100, 100);
item2->setPos(200, 200);

注意:如果需要在运行时动态添加或移除图形项,可以在程序中保存 QGraphicsItem 的指针,然后通过 addItem() 和 removeItem() 函数来添加或移除图形项。同时,为了避免内存泄漏,需要在不需要使用的图形项时手动释放它们的内存。


原文地址: https://www.cveoy.top/t/topic/nLHm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录