简体   繁体   中英

Qt OpenGL texture won't appear

I'm using Qt to create a simple sprite editor with OpenGL, but the image just doesn't show up, it's just a white quad on the screen.

I have checked my code, and I think everything is right. The quad is of the same size of the image and the texture id is not 0.

Here's my code:

Initialization:

glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);

glViewport(0, 0, width, height);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, win_width, win_height, 0, -1, 1);
glMatrixMode(GL_MODELVIEW);

Texture loading:

QImage b = QImage(filename);
m_texture = QGLWidget::convertToGLFormat(b);

glGenTextures(1, &m_id);
glBindTexture(GL_TEXTURE_2D, m_id);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
             m_texture.width(),
             m_texture.height(),
             0, GL_RGBA, GL_UNSIGNED_BYTE,
             m_texture.bits());

Render:

glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);

glBindTexture(GL_TEXTURE_2D, m_id);

glBegin(GL_QUADS);

glTexCoord2f(0.0f, 0.0f);
glVertex2i(0, 0);

glTexCoord2f(1.0f, 0.0f);
glVertex2i(m_texture.width(), 0);

glTexCoord2f(1.0f, 1.0f);
glVertex2i(m_texture.width(), m_texture.height());

glTexCoord2f(0.0f, 1.0f);
glVertex2i(0, m_texture.height());

glEnd();

glBindTexture(GL_TEXTURE_2D, 0);

This is what I'm getting so far: 白色四边形

Try manually setting the OpenGL version to 3.2.

QGLFormat glFormat;
glFormat.setVersion(3, 2);
glFormat.setProfile(QGLFormat::CoreProfile);
QGLFormat::setDefaultFormat(glFormat);

After you do that, print your OpenGL version with glGetString().

If you're still getting 2.1, you didn't set it in the correct OpenGL context. I'm not sure exactly how you're making your OpenGL calls, but I was using QT Creator Designer, and was embedding a QGLWidget within the main window. So I was successfully able to set the OpenGL version by setting it within the MainWindow constructor

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    QGLFormat glFormat;
    glFormat.setVersion(3, 2);
    glFormat.setProfile(QGLFormat::CoreProfile);
    QGLFormat::setDefaultFormat(glFormat);
    ui->setupUi(this);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM