I'm trying to load .obj files into Qt using the Qt3D library. So far I have this code mostly copied from one of the examples:
Qt3DCore::QEntity *createScene()
{
// Root entity
Qt3DCore::QEntity *rootEntity = new Qt3DCore::QEntity;
// Material
Qt3DRender::QMaterial *material = new Qt3DExtras::QPhongMaterial(rootEntity);
// Chest Entity
Qt3DCore::QEntity *chestEntity = new Qt3DCore::QEntity(rootEntity);
Qt3DRender::QMesh *chestMesh = new Qt3DRender::QMesh(rootEntity);
chestMesh->setSource(QUrl("qrc:/PT18E.obj"));
chestEntity->addComponent(chestMesh);
chestEntity->addComponent(material);
return rootEntity;
}
int main(int argc, char* argv[])
{
QGuiApplication app(argc, argv);
Qt3DExtras::Qt3DWindow view;
Qt3DCore::QEntity *scene = createScene();
// Camera
Qt3DRender::QCamera *camera = view.camera();
camera->lens()->setPerspectiveProjection(45.0f, 16.0f/9.0f, 0.1f, 1000.0f);
camera->setPosition(QVector3D(0, 0, 1));
camera->setViewCenter(QVector3D(0, 0, 0));
// For camera controls
Qt3DExtras::QOrbitCameraController *camController = new Qt3DExtras::QOrbitCameraController(scene);
camController->setLinearSpeed( 10.0f );
camController->setLookSpeed( 180.0f );
camController->setCamera(camera);
view.setRootEntity(scene);
view.show();
return app.exec();
}
So far, the application can render the object and display it. However, I had to attach the .obj file to a qrc file in order for it to be able to find and render it. When I try to set the source for the chestMesh
using the absolute path from any directory, e.g.,
chestMesh->setSource(QURL(C:/Users/username/Documents/Qt/simple-cpp/PT18E.obj))
it does not work. Nothing gets rendered and I see the error in the console saying
QFSFileEngine::open: No file name specified
I've tried adding the exact same path to a QFile
object and use the exists
function to see if the path is correct, and sure enough it is. But for some reason the mesh cannot use a source that isn't in a qrc file.
How can I load and render any .obj file from the file system (without having to put it in a qrc) in Qt?