Adding a QGLWidget to a QMainWindow

3k Views Asked by At

I have a MainWindow class with a QGraphicsView which I'd like to add to a MainWindow, so that I'm able to see what's actually going on. All I'm trying to do right now is render a cube.

Main Function

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

MainWindow Ctor

MainWindow::MainWindow( QWidget *parent )
    : QMainWindow( parent ),
      mUi( new Ui::MainWindow ),
      mDisplay( new GLWidget ),
      mScene( new QGraphicsScene )
{
    mUi->setupUi( this );
    //mScene->addWidget( mDisplay );
    QGraphicsView *graphicsView = new QGraphicsView;
    //QGraphicsView::setupViewport( this );
    graphicsView->setViewport( mDisplay );
    graphicsView->show();
}

GLWidget::initializeGL

void GLWidget::initializeGL( void )
{
    glMatrixMode( GL_COLOR );

    glClearColor( 0.0, 0.0, 0.0, 1.0 );

    glMatrixMode( GL_MODELVIEW );

    glClearDepth( 1.0f );

    glEnable( GL_VERTEX_ARRAY );
    glEnable( GL_NORMAL_ARRAY );
    glEnable( GL_DEPTH_TEST );
    glEnable( GL_CULL_FACE );
    glShadeModel( GL_SMOOTH );
    glEnable( GL_LIGHTING );
    glEnable( GL_LIGHT0 );
    glEnable( GL_MULTISAMPLE );
    static GLfloat lightPosition[ 4 ] = { 0.5, 5.0, 7.0, 1.0 };
    glLightfv( GL_LIGHT0, GL_POSITION, lightPosition );

    qDebug() << "GL Initialized" << '\n';
}

As you can see, glClearColor is supposed to set the background to a black screen. The problem is that when I render it, I see two windows which pop up and not one. While the MainWindow class has a window frame which is supposed to render the GLWidget, it appears that, rather than adding it to the window frame, it simply generates both of the frame as well as the window using the QGraphicsView. Both windows only show a white screen; one of them is at least supposed to show a black background, as the glClearColor states.

What am I doing wrong here?

1

There are 1 best solutions below

4
On

glClearColor only sets the color that will be used to clear the screen. To actually clear the screen you must call glCear function:

glClear(GL_COLOR_BUFFER_BIT);

Same thing with glClearDepth - it only sets value of depth to clear with. To actually clear it use the same glCler function. You can clear color buffer and depth buffer with one glClear call like this:

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);