开发者

Creating shader program for QGraphicsItem

开发者 https://www.devze.com 2023-03-13 10:16 出处:网络
I have a QGraphicsScene in which I add a QGraphicsItem. Inside the QGraphicsItem, I render the triangle used in the hello triangle example of OpenGL ES 2.0. The problem is that if I create and compile

I have a QGraphicsScene in which I add a QGraphicsItem. Inside the QGraphicsItem, I render the triangle used in the hello triangle example of OpenGL ES 2.0. The problem is that if I create and compile the shaders anyplace other than the QGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) function, they do not get compiled. I know that you should have a GL rendering context active but doesn't that happen when I set my viewport to a GLWidget?? I tried various things like compiling them in the QGraphicsItem constructor or in the QGraphicsScene and setting the QGraphicsItem as a parent (which I learned they are very stupid things to do), but (obviously) nothing works. What seemed most logical to me was to create a initShaders() function inside the QGraphicsItem class and call it after the item is created in开发者_StackOverflow my scene, but that didn't work also.


Create a derived class of QGraphicsView. Override the setupViewport(QWidget *viewport) to initialize the shaders. This will allow you to ensure the context is current when compiling the shaders. However, it requires that the items be added to the scene before setViewport() is called on the graphics view.

void MyGraphicsView::setupViewport(QWidget *viewport)
{
    QGLWidget *glWidget = qobject_cast<QGLWidget*>(viewport);
    if (glWidget) {
        glWidget->makeCurrent();
        foreach (QGraphicsItem *item, scene()->items())
        {
            MyGraphicsShaderItem *glItem = qgraphicsitem_cast<MyGraphicsShaderItem*>(item);
            if (glItem)
                glItem->initShader();
        }
        glWidget->doneCurrent();
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消