开发者

Seeking advice on using QGLWidget in Qt4

I'm new here, and have a question about opengl in Qt4, which I've been learning over the last few months.

Particularly, I'm seeking advice on the best way to compose a scene in a good object-oriented fashion using the QGLWidget. I'd ideally like every item in my scene to be sub-classes of a super 'Entity' class. Then in my main QGLWidget I can sort the entities and render them accordingly.

I noticed though that certain openGL functions (like bindTexture) need to be called from the QGLWidget (or the widget's QGLContext). At the moment I'm passing a pointer to the QGLWidget that controls my main viewport to each entity and storing it so that I can gain access to those functions. Is this a good idea?

Any advice would be gratefully received, or even dire开发者_Python百科ctions to good websites/books that might be of help. I've got the Blanchette/ Summerfield book but the OpenGL section is quite short and most of the examples on the Qt website are pretty simplistic.

Thanks, Dan


I agree with Vime: You're building a scene graph, and there are a number of classical approaches for designing its object hierarchy. Check out "3D Game Engine Design," by Dave Eberly, for details on one such engine, and look at OGRE for another example.

Since only one GL context can be active at a time on a particular thread, consider storing the QGLWidget pointer as a static class member to save effort:

class MyGLWidget : public QGLWidget {
    // ...
public:
    static inline MyGLWidget *GetActiveWidget() {
        return ms_activeWidget;
    }
protected:
    static __declspec(thread) MyGLWidget *ms_activeWidget = 0; // uses MSVC extension
    inline void SetActiveWidget() {
        ms_activeWidget = this;
    }
};

void MyGLWidget::paintGL() {
    SetActiveWidget();
    // ...
}

Then in your entity classes you can simply call MyGLWidget::GetActiveWidget() on the few occasions when you need to call QGLWidget member functions, and not need to copy a (probably invariant) pointer all over the place.


You are building something that is usually called "scene graph". In our engine scene graph objects need no access to QGLWidget. It's enough if you create your OpenGL objects inside void initializeGL() and render everything inside void paintGL().

There is a slightly higher level Qt/OpenGL example called Boxes. It can be found from qt/demos/boxes folder in Qt 4.6 installation.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜