#include <QtGui> #include <QtOpenGL> #include <QtDeclarative> class MyGraphicsScene: public QGraphicsScene { public: MyGraphicsScene() { // load your QML before drawBackground being called. QmlEngine *engine = new QmlEngine(); QmlComponent component(engine, QUrl::fromLocalFile(qmlfilename)); QGraphicsObject *object = qobject_cast<QGraphicsObject*>(component.create()); addItem(object); // done! that's all. } void drawBackground(QPainter *painter, const QRectF &) { if (painter->paintEngine()->type() != QPaintEngine::OpenGL) { qWarning("OpenGLScene: drawBackground needs a QGLWidget to be set as viewport on the graphics view"); return; } // beginning of OpenGL instructions glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // end of OpenGL instructions QTimer::singleShot(20, this, SLOT(update())); } }
#include "mygraphicsscene.h" #include <QtGui> #include <QGLWidget> class GraphicsView : public QGraphicsView { public: GraphicsView() { setWindowTitle(tr("Hello QML and OpenGL")); } protected: void resizeEvent(QResizeEvent *event) { if (scene()) scene()->setSceneRect( QRect(QPoint(0, 0), event->size())); QGraphicsView::resizeEvent(event); } }; int main(int argc, char **argv) { QApplication app(argc, argv); GraphicsView view; QGLFormat format = QGLFormat::defaultFormat(); // disable AA. format.setSampleBuffers(false); view.setViewport(new QGLWidget(QGLFormat(format))); view.setViewportUpdateMode( QGraphicsView::FullViewportUpdate); view.setScene(new MyGraphicsScene); view.showFullScreen(); view.show(); return app.exec(); }