[英]How to create a translucent/transparent `QOpenGLWindow`
众所周知,要使QWidget
/ QOpenGLWidget
半透明/透明,只需要:
widget->setAttribute(Qt::WA_TranslucentBackground)
但是,由于QWindow
/ QOpenGLWindow
不是小部件并且没有setAttribute
,我不知道如何对QOpenGLWindow
做同样的事情。 我想这在理论上是可能的,因为根据 Qt 的源代码, QWidget
由QWindow
支持。
我在谷歌上搜索但没有太多关于QWindow
透明度的信息
我发现这将通过QSurfaceFormat
和setAlphaBufferSize(8);
在QOpenGLWindow
中发生;
看这个例子:
在主窗口.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
在主窗口.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);
这意味着QOpenGLWindow
或MainWindow
不是QOpenGLContext
。
这将是结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.