Widgets with transparent background over QGraphicsView with QGLWidget viewport

I recently tried setting my window QGraphicsViewon QGLWidgetto see how it works. I noticed that widgets that used to have transparent backgrounds (stylized buttons in game menus that don't have a background) now have a black background. Is there an easy way to maintain transparency and use the viewport QGLWidget?

#include <QtCore>
#include <QtWidgets>
#include <QGLWidget>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QMainWindow mainWindow;

    QGraphicsView *view = new QGraphicsView(&mainWindow);

    view->setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers)));
    view->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);

    QPushButton *button = new QPushButton(&mainWindow);
    button->setStyleSheet("QPushButton {"
      "border: 2px solid #8f8f91;"
      "border-radius: 6px;"
      "background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #f6f7fa, stop: 1 #dadbde);"
      "min-width: 80px;"
      "}");

    QWidget *widget = new QWidget(&mainWindow);
    widget->move(0, 100);

    mainWindow.setCentralWidget(view);
    mainWindow.resize(200, 200);
    mainWindow.show();

    return app.exec();
}

QGL widget black background example

+4
source share
1 answer

According to the resolution of the error report in my comment:

this is an inevitable consequence of how QGLWidget works

Elsewhere it was suggested that it QGraphicsProxyWidgetcould solve the problem:

#include <QtCore>
#include <QtWidgets>
#include <QGLWidget>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QMainWindow mainWindow;

    QGraphicsView *view = new QGraphicsView(&mainWindow);
    QGraphicsScene *scene = new QGraphicsScene;
    view->setScene(scene);

    view->setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers)));
    view->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);

    QPushButton *button = new QPushButton;
    button->setStyleSheet("QPushButton {"
      "border: 2px solid #8f8f91;"
      "border-radius: 6px;"
      "background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #f6f7fa, stop: 1 #dadbde);"
      "min-width: 80px;"
      "}");

    scene->addWidget(button);

    mainWindow.setCentralWidget(view);
    mainWindow.resize(200, 200);
    mainWindow.show();

    return app.exec();
}

qgraphicsproxywidget-screenshot

+2
source

All Articles