Qt 3D:基本形狀 C++ 範例

展示由 Qt 3D 提供的 4 個基本形狀,並為每個形狀設置網格。

基本形狀 shows four basic shapes that Qt 3D offers: a torus, a cylinder, a cube, and a sphere. The example also shows how to embed a Qt 3D scene into a widget and connect with other widgets.

運行範例

要運行範例從 Qt Creator ,打開 歡迎 模式,然後選擇範例從 範例 。更多信息,拜訪 構建和運行範例 .

設置環形網格

例如,瞭解如何設置環形網格。首先,實例化 QTorusMesh , and then we set the mesh specific parameters, which for torus are radius, minor radius, and the number of rings and slices.

m_torus = new Qt3DExtras::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 組件。

Qt3DCore::QTransform *torusTransform = new Qt3DCore::QTransform();
torusTransform->setScale(2.0f);
torusTransform->setRotation(QQuaternion::fromAxisAndAngle(QVector3D(0.0f, 1.0f, 0.0f), 25.0f));
torusTransform->setTranslation(QVector3D(5.0f, 4.0f, 0.0f));
					

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

Qt3DExtras::QPhongMaterial *torusMaterial = new Qt3DExtras::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 a parent entity and adding the previously created mesh, material, and transform components into it.

m_torusEntity = new Qt3DCore::QEntity(m_rootEntity);
m_torusEntity->addComponent(m_torus);
m_torusEntity->addComponent(torusMaterial);
m_torusEntity->addComponent(torusTransform);
					

We can control the visibility of the entity by defining whether it has a parent or not. That is, whether it is part of an entity tree or not.

void SceneModifier::enableTorus(bool enabled)
{
    m_torusEntity->setEnabled(enabled);
}
					

範例工程 @ code.qt.io