Qt 3D:C++ 基本形状示例
展示了Qt 3D 提供的四种基本形状,并为每种形状设置了一个网格。

“基本形状”演示了Qt 3D 提供的四种基本形状:环面、圆柱体、立方体和球体。该示例还展示了如何将Qt 3D 场景嵌入到控件中,并与其他控件进行连接。
运行示例
您可以通过以下方式运行该示例:
- Qt Creator
打开Welcome 模式,并从Examples 中选择该示例。有关更多信息,请参阅Qt Creator :教程:构建和运行。
- Qt Extension for Visual Studio Code
在Command Palette 中运行Qt: Open Qt examples 命令,并从列表中选择该示例。有关更多信息,请参阅Qt Extension for Visual Studio Code :教程:构建和运行。
设置环面网格
作为示例,我们将演示如何设置一个环面网格。首先,我们实例化QTorusMesh ,然后设置网格的特定参数,对于环面而言,这些参数包括半径、小半径以及环数和切片数。
m_torus = new Qt3DExtras::QTorusMesh();
m_torus->setRadius(1.0f);
m_torus->setMinorRadius(0.4f);
m_torus->setRings(100);
m_torus->setSlices(20);环面的大小和位置可通过变换组件进行调整。我们创建缩放、平移和旋转组件,并将它们添加到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));要更改网格的漫反射颜色,我们创建一个QPhongMaterial 并设置其漫反射颜色。
Qt3DExtras::QPhongMaterial *torusMaterial = new Qt3DExtras::QPhongMaterial();
torusMaterial->setDiffuse(QColor(QRgb(0xbeb32b)));最后一步是将环面添加到实体树中,具体操作是创建一个具有父实体的QEntity ,并将之前创建的网格、材质和变换组件添加到其中。
m_torusEntity = new Qt3DCore::QEntity(m_rootEntity);
m_torusEntity->addComponent(m_torus);
m_torusEntity->addComponent(torusMaterial);
m_torusEntity->addComponent(torusTransform);我们可以通过定义该实体是否具有父实体来控制其可见性,即它是否属于实体树的一部分。
void SceneModifier::enableTorus(bool enabled)
{
m_torusEntity->setEnabled(enabled);
}© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.