首页 > 解决方案 > QGraphicsView additem() 越来越大

问题描述

我有一个信号会触发 QT 上的以下插槽:

void MainWindow::stream_frame_changed(bool change, const QImage& image)
{
    if (stream == true && change == true)
    {
        QPixmap aux = QPixmap::fromImage(image);
        item->setPixmap(aux);
        ui->graphicsView->scene()->addItem(item);
    }
}

该信号每 100 毫秒发出一次。我注意到存在内存泄漏,这是有道理的,因为我在场景中添加了许多项目而从未删除它们。

我不知道如何删除以前的项目。如果我执行 clear() 函数,窗口会关闭,所以它显然不是一个选项。

标签: qtqt5

解决方案


您必须重用现有项目,而不是创建新项目:

* .cpp

在构造函数上:

ui->graphicsView->scene()->addItem(item);

void MainWindow::stream_frame_changed(bool change, const QImage& image)
{
    if (stream == true && change == true)
    {
        QPixmap aux = QPixmap::fromImage(image);
        item->setPixmap(aux);
    }
}

推荐阅读