En esta página

QOpenGLFramebufferObject Class

La clase QOpenGLFramebufferObject encapsula un objeto framebuffer OpenGL. Más...

Cabecera: #include <QOpenGLFramebufferObject>
CMake: find_package(Qt6 REQUIRED COMPONENTS OpenGL)
target_link_libraries(mytarget PRIVATE Qt6::OpenGL)
qmake: QT += opengl

Tipos Públicos

enum Attachment { NoAttachment, CombinedDepthStencil, Depth }
enum FramebufferRestorePolicy { DontRestoreFramebufferBinding, RestoreFramebufferBindingToDefault, RestoreFrameBufferBinding }

Funciones Públicas

QOpenGLFramebufferObject(const QSize &size, GLenum target = GL_TEXTURE_2D)
QOpenGLFramebufferObject(const QSize &size, const QOpenGLFramebufferObjectFormat &format)
QOpenGLFramebufferObject(int width, int height, GLenum target = GL_TEXTURE_2D)
QOpenGLFramebufferObject(int width, int height, const QOpenGLFramebufferObjectFormat &format)
QOpenGLFramebufferObject(const QSize &size, QOpenGLFramebufferObject::Attachment attachment, GLenum target = GL_TEXTURE_2D, GLenum internalFormat = 0)
QOpenGLFramebufferObject(int width, int height, QOpenGLFramebufferObject::Attachment attachment, GLenum target = GL_TEXTURE_2D, GLenum internalFormat = 0)
virtual ~QOpenGLFramebufferObject()
void addColorAttachment(const QSize &size, GLenum internalFormat = 0)
void addColorAttachment(int width, int height, GLenum internalFormat = 0)
QOpenGLFramebufferObject::Attachment attachment() const
bool bind()
QOpenGLFramebufferObjectFormat format() const
GLuint handle() const
int height() const
bool isBound() const
bool isValid() const
bool release()
void setAttachment(QOpenGLFramebufferObject::Attachment attachment)
QSize size() const
QList<QSize> sizes() const
GLuint takeTexture()
GLuint takeTexture(int colorAttachmentIndex)
GLuint texture() const
QList<GLuint> textures() const
QImage toImage(bool flipped = true) const
QImage toImage(bool flipped, int colorAttachmentIndex) const
int width() const

Miembros Públicos Estáticos

bool bindDefault()
void blitFramebuffer(QOpenGLFramebufferObject *target, const QRect &targetRect, QOpenGLFramebufferObject *source, const QRect &sourceRect, GLbitfield buffers, GLenum filter, int readColorAttachmentIndex, int drawColorAttachmentIndex, QOpenGLFramebufferObject::FramebufferRestorePolicy restorePolicy)
void blitFramebuffer(QOpenGLFramebufferObject *target, QOpenGLFramebufferObject *source, GLbitfield buffers = GL_COLOR_BUFFER_BIT, GLenum filter = GL_NEAREST)
void blitFramebuffer(QOpenGLFramebufferObject *target, const QRect &targetRect, QOpenGLFramebufferObject *source, const QRect &sourceRect, GLbitfield buffers = GL_COLOR_BUFFER_BIT, GLenum filter = GL_NEAREST)
void blitFramebuffer(QOpenGLFramebufferObject *target, const QRect &targetRect, QOpenGLFramebufferObject *source, const QRect &sourceRect, GLbitfield buffers, GLenum filter, int readColorAttachmentIndex, int drawColorAttachmentIndex)
bool hasOpenGLFramebufferBlit()
bool hasOpenGLFramebufferObjects()

Descripción Detallada

La clase QOpenGLFramebufferObject encapsula un objeto framebuffer OpenGL, definido por la extensión GL_EXT_framebuffer_object. Proporciona una superficie de renderizado sobre la que se puede pintar con QPainter con la ayuda de QOpenGLPaintDevice, o sobre la que se puede renderizar utilizando llamadas OpenGL nativas. Esta superficie puede ser enlazada y usada como una textura normal en tu propio código de dibujo OpenGL. Por defecto, la clase QOpenGLFramebufferObject genera una textura OpenGL 2D (usando el objetivo GL_TEXTURE_2D ), que se usa como objetivo interno de renderizado.

Es importante tener un contexto OpenGL actual cuando se crea un QOpenGLFramebufferObject, de lo contrario la inicializacion fallara.

Cree la instancia QOpenGLFrameBufferObject con el adjunto CombinedDepthStencil si quiere que QPainter renderice correctamente. Ten en cuenta que necesitas crear un QOpenGLFramebufferObject con más de una muestra por pixel para que las primitivas sean antialiased cuando dibujes usando un QPainter. Para crear un objeto framebuffer multimuestra debes usar uno de los constructores que toman un parámetro QOpenGLFramebufferObjectFormat, y establecer la propiedad QOpenGLFramebufferObjectFormat::samples() a un valor distinto de cero.

Para los objetos framebuffer multimuestra se crea un buffer de renderizado de color, de lo contrario se crea una textura con el objetivo de textura especificado. El búfer de renderizado de color o la textura tendrán el formato interno especificado y estarán vinculados al adjunto GL_COLOR_ATTACHMENT0 del objeto framebuffer.

También se admiten múltiples objetivos de renderizado, en caso de que la implementación de OpenGL lo admita. Aquí habrá múltiples texturas (o, en caso de multimuestreo, renderbuffers) presentes y cada una de ellas se adjuntará a GL_COLOR_ATTACHMENT0, 1, 2, ...

Si quieres usar un objeto framebuffer con multimuestreo habilitado como textura, primero necesitas copiarlo a un objeto framebuffer normal usando QOpenGLContext::blitFramebuffer().

Es posible dibujar en un QOpenGLFramebufferObject usando QPainter y QOpenGLPaintDevice en un hilo separado.

Documentación de tipos de miembros

enum QOpenGLFramebufferObject::Attachment

Este tipo enum se utiliza para configurar los buffers de profundidad y stencil adjuntos al objeto framebuffer cuando se crea.

ConstanteValorDescripción
QOpenGLFramebufferObject::NoAttachment0No se añade ningún adjunto al objeto framebuffer. Tenga en cuenta que las pruebas de profundidad y stencil de OpenGL no funcionarán cuando se renderice a un objeto framebuffer sin ningún búfer de profundidad o stencil. Este es el valor por defecto.
QOpenGLFramebufferObject::CombinedDepthStencil1Si la extensión GL_EXT_packed_depth_stencil está presente, se adjunta un búfer combinado de profundidad y esténcil. Si la extensión no está presente, sólo se adjunta un búfer de profundidad.
QOpenGLFramebufferObject::Depth2Se adjunta un búfer de profundidad al objeto framebuffer.

Véase también attachment().

enum QOpenGLFramebufferObject::FramebufferRestorePolicy

Este tipo enum se utiliza para configurar el comportamiento relacionado con la restauración de los bindings del framebuffer cuando se llama a blitFramebuffer().

ConstanteValorDescripción
QOpenGLFramebufferObject::DontRestoreFramebufferBinding0No restaura el framebuffer anterior. La persona que llama es responsable de rastrear y establecer la vinculación del framebuffer según sea necesario.
QOpenGLFramebufferObject::RestoreFramebufferBindingToDefault1Después de la operación blit, vincula el framebuffer por defecto.
QOpenGLFramebufferObject::RestoreFrameBufferBinding2Restaura el framebuffer previamente enlazado. Esto es potencialmente costoso debido a la necesidad de consultar el framebuffer actualmente enlazado.

Véase también blitFramebuffer().

Documentación de las funciones miembro

[explicit] QOpenGLFramebufferObject::QOpenGLFramebufferObject(const QSize &size, GLenum target = GL_TEXTURE_2D)

Construye un objeto framebuffer OpenGL y enlaza una textura 2D OpenGL al buffer del tamaño size. La textura se vincula al destino GL_COLOR_ATTACHMENT0 en el objeto framebuffer.

El parámetro target se utiliza para especificar el destino de la textura OpenGL. El destino por defecto es GL_TEXTURE_2D. Tenga en cuenta que las texturas GL_TEXTURE_2D deben tener una potencia de 2 en anchura y altura (por ejemplo, 256x512), a menos que esté utilizando OpenGL 2.0 o superior.

Por defecto, no se adjuntan buffers de profundidad y stencil. Este comportamiento puede cambiarse utilizando uno de los constructores sobrecargados.

El formato de textura interno por defecto es GL_RGBA8 para OpenGL de escritorio, y GL_RGBA para OpenGL/ES.

Es importante que tengas un contexto OpenGL actual establecido cuando crees el QOpenGLFramebufferObject, de lo contrario la inicializacion fallara.

Ver también size(), texture(), y attachment().

QOpenGLFramebufferObject::QOpenGLFramebufferObject(const QSize &size, const QOpenGLFramebufferObjectFormat &format)

Construye un objeto framebuffer OpenGL con la dirección size basada en la dirección format.

QOpenGLFramebufferObject::QOpenGLFramebufferObject(int width, int height, GLenum target = GL_TEXTURE_2D)

Construye un objeto framebuffer OpenGL y enlaza una textura 2D OpenGL al buffer de los dados width y height.

Véase también size() y texture().

QOpenGLFramebufferObject::QOpenGLFramebufferObject(int width, int height, const QOpenGLFramebufferObjectFormat &format)

Construye un objeto framebuffer OpenGL con los valores width y height basados en format.

QOpenGLFramebufferObject::QOpenGLFramebufferObject(const QSize &size, QOpenGLFramebufferObject::Attachment attachment, GLenum target = GL_TEXTURE_2D, GLenum internalFormat = 0)

Construye un objeto framebuffer OpenGL y vincula una textura al buffer del size dado.

El parámetro attachment describe la configuración del búfer de profundidad/esténcil, target el objetivo de la textura y internalFormat el formato interno de la textura. El objetivo de textura por defecto es GL_TEXTURE_2D, mientras que el formato interno por defecto es GL_RGBA8 para OpenGL de escritorio y GL_RGBA para OpenGL/ES.

Véase también size(), texture(), y attachment().

QOpenGLFramebufferObject::QOpenGLFramebufferObject(int width, int height, QOpenGLFramebufferObject::Attachment attachment, GLenum target = GL_TEXTURE_2D, GLenum internalFormat = 0)

Construye un objeto framebuffer OpenGL y vincula una textura al buffer de los parámetros width y height.

El parámetro attachment describe la configuración del búfer de profundidad/esténcil, target el destino de la textura y internalFormat el formato interno de la textura. El objetivo de textura por defecto es GL_TEXTURE_2D, mientras que el formato interno por defecto es GL_RGBA8 para OpenGL de escritorio y GL_RGBA para OpenGL/ES.

Véase también size(), texture(), y attachment().

[virtual noexcept] QOpenGLFramebufferObject::~QOpenGLFramebufferObject()

Destruye el objeto framebuffer y libera los recursos asignados.

void QOpenGLFramebufferObject::addColorAttachment(const QSize &size, GLenum internalFormat = 0)

Crea y adjunta una textura adicional o renderbuffer de size anchura y altura.

Siempre hay un adjunto en GL_COLOR_ATTACHMENT0. Llama a esta función para crear adjuntos adicionales en GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, ...

Cuando internalFormat no es 0, especifica el formato interno de la textura o renderbuffer. En caso contrario, se utiliza GL_RGBA o GL_RGBA8 por defecto.

Nota: Esto sólo es funcional cuando la implementación de OpenGL soporta múltiples objetivos de renderizado. Si no es el caso, la función no añadirá ningún color adicional. Llame a QOpenGLFunctions::hasOpenGLFeature() con QOpenGLFunctions::MultipleRenderTargets en tiempo de ejecución para comprobar si MRT está soportado.

Nota: El formato interno de los adjuntos de color puede diferir, pero puede haber limitaciones en las combinaciones soportadas, dependiendo de los controladores.

Nota: El tamaño de los anexos de color puede variar, pero la representación se limita al área en la que caben todos los anexos, de acuerdo con la especificación OpenGL. Sin embargo, algunos controladores pueden no ser totalmente conformes a este respecto.

void QOpenGLFramebufferObject::addColorAttachment(int width, int height, GLenum internalFormat = 0)

Crea y adjunta una textura o renderbuffer adicional de tamaño width y height.

Cuando internalFormat no es 0, especifica el formato interno de la textura o renderbuffer. En caso contrario, se utiliza GL_RGBA o GL_RGBA8 por defecto.

Se trata de una función sobrecargada.

QOpenGLFramebufferObject::Attachment QOpenGLFramebufferObject::attachment() const

Devuelve el estado de los buffers de profundidad y stencil adjuntos a este objeto framebuffer.

Véase también setAttachment().

bool QOpenGLFramebufferObject::bind()

Cambia el renderizado del framebuffer por defecto, proporcionado por el sistema de ventanas, a este objeto framebuffer. Devuelve true en caso de éxito, false en caso contrario.

Nota: Si se ha llamado a takeTexture(), se crea una nueva textura y se asocia al objeto framebuffer. Esto es potencialmente costoso y cambia el estado del contexto (la textura actualmente asociada).

Véase también release().

[static] bool QOpenGLFramebufferObject::bindDefault()

Devuelve el renderizado al framebuffer por defecto, proporcionado por el sistema de ventanas. Devuelve true en caso de éxito, false en caso contrario.

Véase también bind() y release().

[static] void QOpenGLFramebufferObject::blitFramebuffer(QOpenGLFramebufferObject *target, const QRect &targetRect, QOpenGLFramebufferObject *source, const QRect &sourceRect, GLbitfield buffers, GLenum filter, int readColorAttachmentIndex, int drawColorAttachmentIndex, QOpenGLFramebufferObject::FramebufferRestorePolicy restorePolicy)

Blits desde el rectángulo sourceRect en el objeto framebuffer source al rectángulo targetRect en el objeto framebuffer target.

Si source o target es 0, se utilizará el framebuffer por defecto en lugar de un objeto framebuffer como origen o destino respectivamente.

Esta función no tendrá efecto a menos que hasOpenGLFramebufferBlit() devuelva verdadero.

El parámetro buffers debe ser una máscara consistente en cualquier combinación de GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, y GL_STENCIL_BUFFER_BIT. Se ignora cualquier tipo de búfer que no esté presente tanto en el búfer de origen como en el de destino.

Los rectángulos sourceRect y targetRect pueden tener tamaños diferentes; en este caso, buffers no debe contener GL_DEPTH_BUFFER_BIT ni GL_STENCIL_BUFFER_BIT. El parámetro filter debe establecerse en GL_LINEAR o GL_NEAREST, y especifica si debe utilizarse la interpolación lineal o la más cercana cuando se realiza el escalado.

Si source es igual a target se realiza una copia dentro del mismo búfer. Los resultados son indefinidos si los rectángulos de origen y destino se solapan y tienen tamaños diferentes. Los tamaños también deben ser iguales si alguno de los objetos del framebuffer es un framebufer multimuestra.

Nota: La prueba de tijera restringirá el área de blit si está activada.

Cuando se utilizan varios objetivos de renderizado, readColorAttachmentIndex y drawColorAttachmentIndex especifican el índice de los adjuntos de color en los framebuffers de origen y destino.

El restorePolicy determina si el framebuffer que estaba ligado antes de llamar a esta función debe ser restaurado, o si el framebuffer por defecto debe ser ligado antes de regresar, o si el que llama es responsable de rastrear y fijar el framebuffer ligado. Restaurar el framebuffer anterior puede ser relativamente caro debido a la llamada a glGetIntegerv, que en algunos controladores OpenGL puede implicar un bloqueo del pipeline.

Véase también hasOpenGLFramebufferBlit().

[static] void QOpenGLFramebufferObject::blitFramebuffer(QOpenGLFramebufferObject *target, QOpenGLFramebufferObject *source, GLbitfield buffers = GL_COLOR_BUFFER_BIT, GLenum filter = GL_NEAREST)

Sobrecarga para mezclar dos objetos framebuffer.

Se trata de una función sobrecargada.

[static] void QOpenGLFramebufferObject::blitFramebuffer(QOpenGLFramebufferObject *target, const QRect &targetRect, QOpenGLFramebufferObject *source, const QRect &sourceRect, GLbitfield buffers = GL_COLOR_BUFFER_BIT, GLenum filter = GL_NEAREST)

* Conveniente sobrecarga para mezclar dos objetos framebuffer.

Esta es una función sobrecargada.

[static] void QOpenGLFramebufferObject::blitFramebuffer(QOpenGLFramebufferObject *target, const QRect &targetRect, QOpenGLFramebufferObject *source, const QRect &sourceRect, GLbitfield buffers, GLenum filter, int readColorAttachmentIndex, int drawColorAttachmentIndex)

Sobrecarga conveniente para mezclar dos objetos framebuffer y restaurar el enlace framebuffer anterior. Equivale a llamar a blitFramebuffer(target, targetRect, source, sourceRect, buffers, filter, readColorAttachmentIndex, drawColorAttachmentIndex, RestoreFrameBufferBinding).

Se trata de una función sobrecargada.

QOpenGLFramebufferObjectFormat QOpenGLFramebufferObject::format() const

Devuelve el formato de este objeto framebuffer.

GLuint QOpenGLFramebufferObject::handle() const

Devuelve el manejador del objeto framebuffer OpenGL para este objeto framebuffer (devuelto por la función glGenFrameBuffersEXT() ). Este manejador se puede utilizar para adjuntar nuevas imágenes o buffers al framebuffer. El usuario es responsable de limpiar y destruir estos objetos.

[static] bool QOpenGLFramebufferObject::hasOpenGLFramebufferBlit()

Devuelve true si la extensión OpenGL GL_EXT_framebuffer_blit está presente en este sistema; en caso contrario devuelve false.

Véase también blitFramebuffer().

[static] bool QOpenGLFramebufferObject::hasOpenGLFramebufferObjects()

Devuelve true si la extensión OpenGL GL_EXT_framebuffer_object está presente en este sistema; en caso contrario devuelve false.

int QOpenGLFramebufferObject::height() const

Devuelve la altura de los adjuntos del objeto framebuffer.

bool QOpenGLFramebufferObject::isBound() const

Devuelve true si el objeto framebuffer está actualmente vinculado al contexto actual, en caso contrario devuelve false.

bool QOpenGLFramebufferObject::isValid() const

Devuelve true si el objeto framebuffer es válido.

El framebuffer puede volverse inválido si el proceso de inicialización falla, si el usuario adjunta un buffer inválido al objeto framebuffer, o si se especifica una anchura/altura no-potencia de dos como tamaño de la textura si el objetivo de la textura es GL_TEXTURE_2D. La limitación de no potencia de dos no se aplica si la versión de OpenGL es 2.0 o superior, o si la extensión GL_ARB_texture_non_power_of_two está presente.

El framebuffer también puede dejar de ser válido si el QOpenGLContext dentro del cual se creó el framebuffer se destruye y no hay otros contextos compartidos que puedan asumir la propiedad del framebuffer.

bool QOpenGLFramebufferObject::release()

Devuelve el renderizado al framebuffer por defecto, proporcionado por el sistema de ventanas. Devuelve true en caso de éxito, false en caso contrario.

Véase también bind().

void QOpenGLFramebufferObject::setAttachment(QOpenGLFramebufferObject::Attachment attachment)

Establece los adjuntos del objeto framebuffer en attachment.

Esto se puede utilizar para liberar o volver a adjuntar los adjuntos del buffer de profundidad y del stencil según sea necesario.

Nota: Esta función altera la vinculación actual del framebuffer.

Véase también attachment().

QSize QOpenGLFramebufferObject::size() const

Devuelve el tamaño de los adjuntos de color y profundidad/esténcil adjuntos a este objeto framebuffer.

QList<QSize> QOpenGLFramebufferObject::sizes() const

Devuelve los tamaños de todos los anexos de color adjuntos a este objeto framebuffer.

GLuint QOpenGLFramebufferObject::takeTexture()

Devuelve el id de la textura adjunta a este objeto framebuffer. La propiedad de la textura se transfiere al llamante.

Si el objeto framebuffer está actualmente enlazado, se realizará una release() implícita. Durante la siguiente llamada a bind() se creará una nueva textura.

Si se utiliza un objeto framebuffer multimuestra, entonces no hay textura y el valor de retorno de esta función será inválido. Del mismo modo, los objetos framebuffer incompletos también devolverán 0.

Véase también texture(), bind(), y release().

GLuint QOpenGLFramebufferObject::takeTexture(int colorAttachmentIndex)

Devuelve el id de textura para la textura adjunta al adjunto de color del índice colorAttachmentIndex de este objeto framebuffer. La propiedad de la textura se transfiere al llamante.

Cuando colorAttachmentIndex es 0, el comportamiento es idéntico a la variante sin parámetros de esta función.

Si el objeto framebuffer está actualmente enlazado, se realizará una release() implícita. Durante la siguiente llamada a bind() se creará una nueva textura.

Si se utiliza un objeto framebuffer multimuestra, entonces no habrá textura y el valor de retorno de esta función no será válido. De forma similar, los objetos framebuffer incompletos también devolverán 0.

Esta es una función sobrecargada.

GLuint QOpenGLFramebufferObject::texture() const

Devuelve el id de la textura adjunta como objetivo de renderizado por defecto en este objeto framebuffer. Este id de textura puede ser enlazado como una textura normal en su propio código OpenGL.

Si se utiliza un objeto framebuffer multimuestra, el valor devuelto por esta función no será válido.

Cuando se adjuntan múltiples texturas, el valor devuelto es el ID de la primera.

Véase también takeTexture() y textures().

QList<GLuint> QOpenGLFramebufferObject::textures() const

Devuelve el id de textura para todas las texturas adjuntas.

Si se utiliza un objeto framebuffer multimuestra, se devuelve un vector vacío.

Véase también takeTexture() y texture().

QImage QOpenGLFramebufferObject::toImage(bool flipped = true) const

Devuelve el contenido de este objeto framebuffer como QImage.

Si flipped es verdadero, la imagen se voltea de coordenadas OpenGL a coordenadas raster. Si se utiliza junto con QOpenGLPaintDevice, flipped debe ser el valor opuesto al de QOpenGLPaintDevice::paintFlipped().

La imagen devuelta tiene un formato de ARGB32 premultiplicado o RGB32. Este último sólo se usa cuando internalTextureFormat() está establecido a GL_RGB. Desde Qt 5.2 la función volverá a RGBA8888 premultiplicado o RGBx8888 cuando la lectura a (A)RGB32 no esté soportada, y esto incluye OpenGL ES. Desde Qt 5.4 se devuelve una imagen A2BGR30 si el formato interno es RGB10_A2, y desde Qt 5.12 se devuelve una imagen RGBA64 si el formato interno es RGBA16.

Si el renderizado en el framebuffer no se hizo teniendo en cuenta el alfa premultiplicado, crea un wrapper QImage con un formato no premultiplicado. Esto es necesario antes de realizar operaciones como QImage::save() porque si no los datos de la imagen se despremultiplicarían, aunque no estuvieran premultiplicados en primer lugar. Para crear una envoltura de este tipo sin realizar una copia de los datos de píxeles, haga lo siguiente:

QImage fboImage(fbo.toImage());
QImage image(fboImage.constBits(), fboImage.width(), fboImage.height(), QImage::Format_ARGB32);

Para objetos framebuffer multimuestreados, las muestras se resuelven utilizando la extensión GL_EXT_framebuffer_blit. Si la extensión no está disponible, el contenido de la imagen devuelta es indefinido.

Para framebuffers de una sola muestra, el contenido se recupera a través de glReadPixels. Se trata de una operación potencialmente cara e ineficiente. Por lo tanto, se recomienda utilizar esta función lo menos posible.

Véase también QOpenGLPaintDevice::paintFlipped().

QImage QOpenGLFramebufferObject::toImage(bool flipped, int colorAttachmentIndex) const

Devuelve el contenido del adjunto de color del índice colorAttachmentIndex de este objeto framebuffer como QImage. Este método invierte la imagen de coordenadas OpenGL a coordenadas raster cuando flipped se establece en true.

Nota: Esta sobrecarga sólo es completamente funcional cuando la implementación de OpenGL soporta múltiples objetivos de renderizado. Si no es el caso, sólo se establecerá un color adjunto.

Esta es una función sobrecargada.

int QOpenGLFramebufferObject::width() const

Devuelve la anchura de los anexos del objeto framebuffer.

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.