gpt4 book ai didi

c++ - 如何创建半透明/透明 `QOpenGLWindow`

转载 作者:行者123 更新时间:2023-12-05 05:30:33 71 4
gpt4 key购买 nike

众所周知,要使QWidget/QOpenGLWidget半透明/透明,只需:

widget->setAttribute(Qt::WA_TranslucentBackground)

但是,由于 QWindow/QOpenGLWindow 不是一个小部件并且没有 setAttribute,我不知道该怎么做QOpenGLWindow 也是如此。我想这在理论上是可能的,因为根据 Qt 的源代码,QWidgetQWindow 支持。

我在谷歌上搜索过关于QWindow透明度的信息不多

最佳答案

我发现这会在 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();
}

I w.setFormat(format); 这意味着 QOpenGLWindowMainWindow 不是 QOpenGLContext .

这将是结果:

enter image description here

关于c++ - 如何创建半透明/透明 `QOpenGLWindow`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74636126/

71 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com