Qt World Summit: Register Today!

Update OpenGL buffer data using memcpy

  • Hi,

    I'm using QOpenGLWidget in Qt5.10.1 drawing objects only when the vertices change. I have a clean() function connected to a button that can be used to clean the scene. Please note I only memcpy the vertices data when data comes (see the code below: if (data_comes) {...}), Problem is: even when there is no data comes, my clean button still works, i.e. the scene has been cleaned. I have tested, when I click clean button, the program does not go into if(data_comes) loop, meaning no vertices data is memcpied. Then why the scene is still cleaned?

    In my initializeGL():

        if (m_vao.isCreated())
        if (m_vboPos.isCreated()) {
            m_vboPos.allocate(NUM_SAMPLING * sizeof(QVector3D));
            glVertexAttribPointer(m_posAttr, 3, GL_FLOAT, GL_FALSE, 0, 0);

    In my paintGL():

        if (data_comes) {
            GLfloat* PosBuffer = (GLfloat*) (m_vboPos.map(QOpenGLBuffer::WriteOnly));
            if (PosBuffer != (GLfloat*) NULL) {
                memcpy(PosBuffer, m_Vertices.constData(), m_Vertices.size() * sizeof(QVector3D));
        } else {
          // Handle not being able to map the buffer
        // Draw
        glDrawArrays(GL_LINE_STRIP, 0, m_Vertices.size());

    In my clean():


  • Lifetime Qt Champion

    @dalishi said in Update OpenGL buffer data using memcpy:


    Where do you set it to true and where do you set it to false?

  • Hi Jsulm,
    In my paintGL(), I have a function to update the vertices data, which listens to another thread. If data comes, this function updates the vertices and returns true. If no data comes, it returns false.

    void MyOpenGL::paintGL() {
        bool data_comes = updateVertices();

  • In if condition you have to disable the button when no data comes that might be helpful to you.

  • @jsulm I think i found why. In my clean(), the m_Vertices.size() becomes 0 and then glDrawArrays(GL_LINE_STRIP, 0, m_Vertices.size()); will draw 0 points.

  • Lifetime Qt Champion

    This post is deleted!

  • @Prince_0912 Thanks. I should say "no new data comes". With the old data, i still want to have clean() function.

  • @dalishi Ok i glad that you track down fault in your code.

Log in to reply