The callback example

callback

Using the Qt signal-slot mechanism to connect a QGLViewer to your scene.

This very simple application uses the Qt signal-slot callback mechanism to link the QGLViewer and your Scene. The two class hence remain totally independent. The drawNeeded() QGLViewer signal is connected to the Scene drawScene() slot.

callback.h

#include <qobject.h>

class QGLViewer;

// The Scene class must derive from QObject in order to allow a
// signal slot mechanism.
class Scene : public QObject {
  Q_OBJECT

public:
  Scene(const QGLViewer *const v);

public Q_SLOTS:
  void draw();
};

callback.cpp

#include "callback.h"
#include <QGLViewer/qglviewer.h>
#include <math.h>

Scene::Scene(const QGLViewer *const v) {
  // Connect the viewer signal to our draw slot.
  connect(v, SIGNAL(drawNeeded()), this, SLOT(draw()));
}

// Draws a spiral
void Scene::draw() {
  const float nbSteps = 200.0;
  glBegin(GL_QUAD_STRIP);
  for (float i = 0; i < nbSteps; ++i) {
    float ratio = i / nbSteps;
    float angle = 21.0 * ratio;
    float c = cos(angle);
    float s = sin(angle);
    float r1 = 1.0 - 0.8 * ratio;
    float r2 = 0.8 - 0.8 * ratio;
    float alt = ratio - 0.5;
    const float nor = .5;
    const float up = sqrt(1.0 - nor * nor);
    glColor3f(1.0 - ratio, 0.2f, ratio);
    glNormal3f(nor * c, up, nor * s);
    glVertex3f(r1 * c, alt, r1 * s);
    glVertex3f(r2 * c, alt + 0.05, r2 * s);
  }
  glEnd();
}

main.cpp

#include "callback.h"
#include <QGLViewer/qglviewer.h>
#include <qapplication.h>
#include <qmessagebox.h>

using namespace std;

void help() {
  QString text("<h2>C a l l b a c k</h2>");
  text += "This example is conceptually the same as simpleViewer.<br>";
  text += "The difference is that it uses the Qt signal/slot mechanism ";
  text += "instead of deriving the QGLViewer class. ";
  text += "The QGLViewer::drawNeeded() signal is connected to the "
          "Scene::draw() method. ";
  text += "The two classes are otherwise completely independant.";

  QMessageBox::information(NULL, "Callback exemple", text);
}

int main(int argc, char **argv) {
  QApplication application(argc, argv);

  // Instantiate the viewer.
  QGLViewer viewer;

  // Restore the previous viewer state.
  viewer.restoreStateFromFile();

  // Create a scene, giving a pointer to the associated viewer.
  Scene s(&viewer);

  viewer.setWindowTitle("callback");

  help();

  viewer.show();

  return application.exec();
}

Back to the examples main page.