具有透明背景的小部件在具有QGLWidget视口的QGraphicsView上

时间:2014-01-01 10:54:38

标签: qt qgraphicsview qglwidget

我最近尝试将QGraphicsView的视口设置为QGLWidget以查看其效果。我注意到,之前具有透明背景的小部件(样式按钮,没有背景的游戏内菜单)现在具有黑色背景。是否有一种简单的方法来保持透明度并仍然使用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();
}

QGLWidget black background example

1 个答案:

答案 0 :(得分:2)

根据我评论中的错误报告的解决方案:

  

这是QGLWidget如何工作的不可避免的结果

有人在其他地方建议QGraphicsProxyWidget可以解决问题:

#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