如何创建一个半透明/透明的`QOpenGLWindow`。

3
众所周知,要使 QWidget/QOpenGLWidget 成为半透明/透明,只需要进行以下操作:
widget->setAttribute(Qt::WA_TranslucentBackground)

然而,由于 QWindow/QOpenGLWindow 不是小部件,也没有 setAttribute,因此我不知道如何为 QOpenGLWindow 实现相同的效果。根据 Qt 的源代码,我猜这理论上是可能的,因为 QWidget 是由 QWindow 支持的。
我在谷歌上搜过,但关于 QWindow 透明度的信息并不多。

我会使用一个没有父级的QOpenGLWidget,并设置属性。你是否因为某些原因被迫使用QWindow版本? - Axel Mancino
@AxelMancino 当然我可以使用 QOpenGLWidget,而且它对我来说很有效。但是我听说 QOpenGLWindow 有点“更高效”,我想探索更多可能性。 - test failed in 1.08s
1个回答

1
我发现这将会在QOpenGLWindow中通过QSurfaceFormatsetAlphaBufferSize(8);发生。
看这个例子:
在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

在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();
}

最后在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();
}


我使用了w.setFormat(format);,这意味着QOpenGLWindowMainWindow会受到影响,而不是QOpenGLContext以下是结果:

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接