简体   繁体   English

如何创建半透明/透明的`QOpenGLWindow`

[英]How to create a translucent/transparent `QOpenGLWindow`

As is widely known that, to make a QWidget / QOpenGLWidget translucent/transparent, one only needs to:众所周知,要使QWidget / QOpenGLWidget半透明/透明,只需要:

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 .但是,由于QWindow / QOpenGLWindow不是小部件并且没有setAttribute ,我不知道如何对QOpenGLWindow做同样的事情。 I guess this is theoretically possible since QWidget is backed by a QWindow according to Qt's source code.我想这在理论上是可能的,因为根据 Qt 的源代码, QWidgetQWindow支持。

I searched on Google but there's not much information about the transparency of QWindow我在谷歌上搜索但没有太多关于QWindow透明度的信息

I found out that this will happen in QOpenGLWindow by QSurfaceFormat and setAlphaBufferSize(8);我发现这将通过QSurfaceFormatsetAlphaBufferSize(8);QOpenGLWindow中发生;

Look at this example:看这个例子:

in mainwindow.h在主窗口.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在主窗口.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最后在 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);w.setFormat(format); which means that QOpenGLWindow or MainWindow not QOpenGLContext .这意味着QOpenGLWindowMainWindow不是QOpenGLContext

This will be the Result:这将是结果:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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