Qt3D: Basic Shapes C++ Example

The Basic Shapes examples shows four basic shapes that Qt3D offers, a torus, a cylinder, a cube and a sphere. The example also shows how to embed a Qt3D scene into a widget and connect with other widgets.

As an example let's go through how to set up a torus mesh. First instantiate the QTorusMesh, and then set the mesh specific parameters, that for torus are radius, minor radius and how many rings and slices.

m_torus = new Qt3D::QTorusMesh();
m_torus->setRadius(1.0f);
m_torus->setMinorRadius(0.4f);
m_torus->setRings(100);
m_torus->setSlices(20);

The size and position of the torus can be adjusted with transform components. We create scale, translation and rotation components and add them into the QTransform component.

Qt3D::QScaleTransform *torusScale = new Qt3D::QScaleTransform();
Qt3D::QTranslateTransform *torusTranslation = new Qt3D::QTranslateTransform();
Qt3D::QRotateTransform *torusRotation = new Qt3D::QRotateTransform();
Qt3D::QTransform *torusTransforms = new Qt3D::QTransform();

torusScale->setScale3D(QVector3D(2.0f, 2.0f, 2.0f));
torusTranslation->setTranslation(QVector3D(1.7f, 1.7f, 0.0f));
torusRotation->setAngleDeg(25.0f);
torusRotation->setAxis(QVector3D(0, 1, 0));

torusTransforms->addTransform(torusRotation);
torusTransforms->addTransform(torusTranslation);
torusTransforms->addTransform(torusScale);

To change the diffuse color of the mesh we create a QPhongMaterial and set its diffuse color.

Qt3D::QPhongMaterial *torusMaterial = new Qt3D::QPhongMaterial();
torusMaterial->setDiffuse(QColor(QRgb(0xbeb32b)));

The final step is to add the torus into an entity tree, and we do that by creating a QEntity with parent entity and adding the previously created mesh, material and transform components into it.

m_torusEntity = new Qt3D::QEntity(m_rootEntity);
m_torusEntity->addComponent(m_torus);
m_torusEntity->addComponent(torusMaterial);
m_torusEntity->addComponent(torusTransforms);

You can control the visibility of the entity by defining if it has parent or not, i.e. whether it is part of entity tree or not.

void SceneModifier::enableTorus(bool enabled)
{
    m_torusEntity->setParent(enabled ? m_rootEntity : Q_NULLPTR);
}

Files: