How to create a translucent/transparent `QOpenGLWindow`

258 views Asked by At

As is widely known that, to make a QWidget/QOpenGLWidget translucent/transparent, one only needs to:

widget->setAttribute(Qt::WA_TranslucentBackground)

However, since QWindow/QOpenGLWindow is not a widget and doesn't have setAttribute, I don't know how to do the same for a QOpenGLWindow. I guess this is theoretically possible since QWidget is backed by a QWindow according to Qt's source code.

I searched on Google but there's not much information about the transparency of QWindow

1

There are 1 answers

0
Parisa.H.R On BEST ANSWER

I found out that this will happen in QOpenGLWindow by QSurfaceFormat and setAlphaBufferSize(8);

Look at this example:

in mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QOpenGLWindow>


class MainWindow: public QOpenGLWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);

    ~MainWindow();


    // QOpenGLWindow interface

protected:
    void  initializeGL();

    void  resizeGL(int w, int h);

    void  paintGL();

    // QWindow interface
    void  resizeEvent(QResizeEvent *);

    // QPaintDeviceWindow interface

    void  paintEvent(QPaintEvent *event);
};

#endif // MAINWINDOW_H

in mainwindow.cpp

#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
{
}

MainWindow::~MainWindow()
{
}

void  MainWindow::initializeGL()
{
    // Set the transparency to the scene to use the transparency of the fragment shader
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    // set the background color = clear color
    glClearColor(0.0f, 0.0f, 0.0f, .0f);
    glClear(GL_COLOR_BUFFER_BIT);
}

void  MainWindow::resizeGL(int w, int h)
{
}

void  MainWindow::paintGL()
{
}

void  MainWindow::resizeEvent(QResizeEvent *)
{
}

void  MainWindow::paintEvent(QPaintEvent *event)
{
    paintGL();
}

and finally in main.cpp

#include "mainwindow.h"

#include <QGuiApplication>

int  main(int argc, char *argv[])
{
    QGuiApplication  app(argc, argv);
    QSurfaceFormat   format;

    format.setRenderableType(QSurfaceFormat::OpenGL);
    format.setProfile(QSurfaceFormat::CoreProfile);
    format.setVersion(3, 3);
    format.setAlphaBufferSize(8);

    MainWindow  w;
    w.setFormat(format);
    w.resize(640, 480);
    w.show();

    return app.exec();
}

I w.setFormat(format); which means that QOpenGLWindow or MainWindow not QOpenGLContext.

This will be the Result:

enter image description here