I’ve a 2D instead of 3D screen when using QOpenGLWidget

  Kiến thức lập trình

I tried to add a 3D widget to an existing widget and added some rendering, but the problem is that when I run the code, I see no cube, just a simple rectangle.

The code compiles and runs successfully

I add some glVertex3f() to draw the cube, I avoid to write the 45 lines in order to not make the code bigger

#include <QtWidgets>
#include <QOpenGLWidget>
#include <QOpenGLFunctions>

class MyOpenGLWidget : public QOpenGLWidget, protected QOpenGLFunctions {
public:
    MyOpenGLWidget(QWidget *parent = nullptr) : QOpenGLWidget(parent) {}

protected:
    void initializeGL() override {
        initializeOpenGLFunctions();
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    }

    void resizeGL(int w, int h) override {
        glViewport(0, 0, w, h);
    }

    void paintGL() override {
       glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

       // Set up projection matrix
       glMatrixMode(GL_PROJECTION);
       glLoadIdentity();
       glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);

       // Set up model-view matrix
       glMatrixMode(GL_MODELVIEW);
       glLoadIdentity();

       // Rotate the cube
       glRotatef(rotationAngle, 1.0f, 1.0f, 1.0f);

       // Draw a cube
       glBegin(GL_QUADS);
       glColor3f(1.0f, 0.5f, 0.0f); // Orange
       // Here 45 glVertex3f() 
       glEnd();
    }

private:
    float rotationAngle = 0.0f;
};
class MainWindow : public QMainWindow {
    public:
        MainWindow(QWidget *parent = nullptr) : QMainWindow(parent) {
            auto centralWidget = new QWidget(this);
            setCentralWidget(centralWidget);
    
            auto layout = new QVBoxLayout(centralWidget);
            auto openGLWidget = new MyOpenGLWidget(this);
            layout->addWidget(openGLWidget);
    
            // Timer for animation
            QTimer *timer = new QTimer(this);
            connect(timer, &QTimer::timeout, [openGLWidget]() {
                openGLWidget->update();
            });
            timer->start(16); // Update roughly every 16 ms for ~60 FPS
        }
};

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

LEAVE A COMMENT