Qt中如何更新QGraphicsScene?生命游戏细胞逐次显示异常问题咨询
问题原因
- Qt是事件驱动型框架,所有界面的实际渲染都依赖
QApplication::exec()启动的主事件循环。你在prog.exec()执行前提交的所有界面操作(包括第一次场景更新、窗口显示)都只是暂存了请求,并没有真的完成屏幕绘制。你在事件循环启动前就已经把第二个细胞设为存活状态,等事件循环启动后第一次渲染就会同时显示两个细胞。 - 你写的空for循环不是有效的延时逻辑,不仅不会触发等待,反而会阻塞主线程,进一步阻碍界面渲染流程。
- 额外隐患:你当前的
updateScene方法每次调用都会往场景中新增QGraphicsRectItem对象,旧的细胞元素不会被删除,长期运行会出现内存泄漏、渲染重叠问题。
修复方案
- 使用
QTimer::singleShot实现非阻塞的500ms延时,把修改第二个细胞、二次更新场景的逻辑放到延时回调中,保证第一次界面渲染完成后再执行后续操作。 - 优化场景更新逻辑,每次重绘细胞前先删除旧的细胞元素,避免重复创建。
修复后参考代码
#include "mainwindow.h" #include <vector> #include <iostream> #include <QApplication> #include <QGraphicsScene> #include <QGraphicsView> #include <QTimer> using namespace std; // 全局变量: const int WIDTH = 600; const int HEIGHT = 400; const int SIZE = 10; const int NCOL = HEIGHT/SIZE; const QColor aliveCol = QColor(200,200,200); const QColor deadCol = QColor(50,50,50); class Cell { public: int x; int y; bool alive; vector<Cell> neigh; Cell(int a = 0, int b = 0) { x = a; y = b; alive = false; neigh = {}; } void draw(QGraphicsScene * scene){ QGraphicsRectItem * cell1 = new QGraphicsRectItem(this->x*SIZE,this->y*SIZE,SIZE,SIZE); // 给细胞元素加标识,方便后续清理 cell1->setData(0, "cell"); if (this->alive) { cell1->setBrush(QBrush(aliveCol)); } else { cell1->setBrush(QBrush(deadCol)); } scene->addItem(cell1); } }; void updateScene (Cell mat [NCOL][NCOL], QGraphicsScene * scene) { // 先删除旧的细胞元素 QList<QGraphicsItem*> items = scene->items(); for(auto item : items) { if(item->data(0) == "cell") { scene->removeItem(item); delete item; } } // 绘制新的细胞状态 for (int i = 0; i<NCOL; i++) { for (int j = 0; j<NCOL; j++) { mat[i][j].draw(scene); } } } int main(int argc, char *argv[]) { QApplication prog(argc, argv); QGraphicsScene * scene = new QGraphicsScene(0,0,WIDTH,HEIGHT); //背景: scene->setBackgroundBrush(Qt::gray); //构建棋盘 for (int i = 0; i <= NCOL; i++){ scene->addLine(SIZE*i,0,SIZE*i,HEIGHT); scene->addLine(0,SIZE*i,HEIGHT,SIZE*i); } //构建细胞矩阵: Cell mat [NCOL][NCOL]={}; for (int i = 0; i<NCOL; i++) { for (int j = 0; j<NCOL; j++) { mat[i][j] = Cell(i,j); } } // 第一步:设置第一个细胞存活,更新场景 mat[9][7].alive = true; updateScene(mat,scene); // 显示窗口 QGraphicsView * view = new QGraphicsView(scene); view->setFixedSize(610,410); view->show(); // 第二步:500ms延时后修改第二个细胞并更新场景 QTimer::singleShot(500, [&](){ mat[20][30].alive = true; updateScene(mat,scene); scene->advance(); scene->update(); }); return prog.exec(); }
内容的提问来源于stack exchange,提问作者Luis Fonseca
相关产品推荐
相关产品推荐

