Draw texture in QQuickPaintedItem
-
@#ifndef GLITEM_H
#define GLITEM_H#include <QOpenGLFunctions>
#include <QQuickPaintedItem>
#include <QtOpenGL>class GLItem : public QQuickPaintedItem, protected QOpenGLFunctions
{
Q_OBJECT
private:GLuint texID[1];
public:
explicit GLItem(QQuickItem *parent = 0);void paint(QPainter *painter); bool init();
private:
int m_prog;
};#endif // GLITEM_H
@@
#include "glitem.h"
#include <QPainter>
#include <QtGui/QOpenGLShaderProgram>
#include <QtGui/QOpenGLContext>
#include <QDebug>GLItem::GLItem(QQuickItem *parent)
: QQuickPaintedItem(parent)
, m_prog(0)
{
setRenderTarget(QQuickPaintedItem::InvertedYFramebufferObject);
}
bool GLItem::init()
{
glGenTextures(1,texID);
initializeOpenGLFunctions();
qDebug() << "init";
}void GLItem::paint(QPainter *painter)
{
painter->beginNativePainting();glClearColor(0.5f,0.0f,1.0f,255); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); float data[256*256*3]; for(int i = 0; i != 256*256*3; i++) { data[i] = (rand() % 1000)/1000.0f; } glActiveTexture(GL_TEXTURE0+0); glBindTexture(GL_TEXTURE_2D, texID[0]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, 256, 256, 0, GL_RGB, GL_FLOAT, data); glEnable(GL_TEXTURE_2D); float vTextureCoord[4][2]; vTextureCoord[0][0] = 0.0f; vTextureCoord[0][1] = 0.0f; vTextureCoord[1][0] = 1.0f; vTextureCoord[1][1] = 0.0f; vTextureCoord[2][0] = 0.0f; vTextureCoord[2][1] = 1.0f; vTextureCoord[3][0] = 1.0f; vTextureCoord[3][1] = 1.0f; float vVertexCoord[4][2]; vVertexCoord[0][0] = 0.0f; vVertexCoord[0][1] = 0.0f; vVertexCoord[1][0] = 600.0f; vVertexCoord[1][1] = 0.0f; vVertexCoord[2][0] = 0.0f; vVertexCoord[2][1] = 600.0f; vVertexCoord[3][0] = 600.0f; vVertexCoord[3][1] = 600.0f; glTexCoordPointer(2, GL_FLOAT, 0, vTextureCoord); glVertexPointer(2, GL_FLOAT, 0, vVertexCoord); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisable(GL_TEXTURE_2D);
}
@The program crashes with error:
ASSERT: "QOpenGLFunctions::isInitialized(d_ptr)"
Also functions glDrawArrays, makeCurrent(), glActiveTexture(...) don't want to work, function init() never calls and I can't initialize function initializeGL(...)
what I'm doing wrong, this code works fine with QGLWidget.. -
Why use QPainter? QtQuick already has helper methods for drawing textures, no need to dive into QPainter and OpenGL code. You can see an example here: "link":https://github.com/sierdzio/closecombatfree/blob/master/src/qmlBase/ccfqmlbasemap.cpp#L66.