Search code examples
c++qtopengl-esqt4qt5

QT5 - multiple OpenGL widgets in the same window


I have developed a basic graphical engine monitoring application using OpenGL ES. It draws basic 2D geometry. I am interested in porting this to QT5 for the cross-platform comparability.

I want to turn each gauge into an individual widget with it's own signals and slots. QT provides a nice example of how to make an OpenGL widget. However, this method makes a new window for each widget. It there a method to make each gauge it's own widget and draw them all in the same window?


Solution

  • QOpenGLWidget is a widget so you can place it inside another widget, in the example when creating a single widget this will be the window. You can create some QMainWindow, QDialog or QWidget and place within them a QOpenGLWidget, the following is an example of how to do it, just replace this main to the main example:

    #include <QApplication>
    #include <QDialog>
    #include <QLabel>
    #include <QSurfaceFormat>
    #include <QVBoxLayout>
    
    #ifndef QT_NO_OPENGL
    #include "mainwidget.h"
    #endif
    
    int main(int argc, char *argv[])
    {
        QApplication app(argc, argv);
    
        QSurfaceFormat format;
        format.setDepthBufferSize(24);
        QSurfaceFormat::setDefaultFormat(format);
    
        app.setApplicationName("cube");
        app.setApplicationVersion("0.1");
    #ifndef QT_NO_OPENGL
        QDialog w;
        QHBoxLayout *lay = new QHBoxLayout(&w);
        QHBoxLayout *hlay = new QHBoxLayout;
        hlay->addWidget(new MainWidget(&w));
        hlay->addWidget(new MainWidget(&w));
        QVBoxLayout *vlay = new QVBoxLayout;
        vlay->addLayout(hlay);
        vlay->addWidget(new MainWidget(&w));
        lay->addWidget(new MainWidget(&w));
        lay->addLayout(vlay);
        w.resize(640, 480);
        w.show();
    #else
        QLabel note("OpenGL Support required");
        note.show();
    #endif
        return app.exec();
    }
    

    Output:

    enter image description here