Qt在QGraphicsView中使⽤opengl不能够刷新的解决⽅案
症状
在QGraphicsView的事件中,不论使⽤ update,repaint,抑或updateScence,resetCacheContent,均不可以刷新界⾯
程序⾥参考上⼀篇博⽂的⽅法,在QGraphicsView中使⽤了Opengl,即,把QGraphicsView的视⼝委托给QGLWidget来渲染参考资料
⼀个⽐⼀个坑爹,都不管⽤
解决⽅案
调⽤ viewport 的update函数
参考代码
⾸先,把QGLWidget绑定到QGraphicsView上,从⽽可以使⽤opengl进⾏渲染
1void MYGraphicsView::setRenderGLWidget(QGLWidget *widget)
2 {
3this->setViewport(widget);
4this->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
5 }
在 drawBackground 函数中使⽤opengl画图
1void MYGraphicsView::drawBackground(QPainter *,const QRectF &)
2 {
3    glClearColor(1,1,1,1);
4    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
5
6    glMatrixMode(GL_PROJECTION);
7    glPushMatrix();
8    glLoadIdentity();
9    gluOrtho2D(0,1,0,1);
10
11    glMatrixMode(GL_MODELVIEW);
12    glPushMatrix();
qt viewport13    glLoadIdentity();
14
15    glColor3f(0,0,0);
16    glLineWidth(2);
17
18float margin=0.05;
19float l=margin,r=1-margin,b=margin,t=1-margin;
20int splitNum=9;
21float dx=(1-margin*2)/(splitNum+1);
22
23    glBegin(GL_LINE_LOOP);
24        glVertex2f(l,b);
25        glVertex2f(l,t);
26        glVertex2f(r,t);
27        glVertex2f(r,b);
28    glEnd();
29
30    glBegin(GL_LINES);
31for(int i=1;i<=splitNum;++i)
32    {
33        glVertex2f(l,b+dx*i);
34        glVertex2f(r,b+dx*i);
35        glVertex2f(l+dx*i,b);
36        glVertex2f(l+dx*i,t);
37    }
38    glEnd();
39    glPopMatrix();
40
41    glMatrixMode(GL_PROJECTION);
42    glPopMatrix();
43 }
最后,事件更新
1void MYGraphicsView::wheelEvent( QWheelEvent * event ) 2 {
3double factor=event->delta()>0?1.1:1/1.1;
4    mpiMsg.scale.x*=factor;
5    mpiMsg.scale.y=mpiMsg.scale.x;
6  this->viewport()->update();
7
8    mpiMsg.broadCast(M*N);
9    MPI_Barrier(MPI_COMM_WORLD);
10 }