qtpyqtqt3d

How to create and apply texture to object in Qt3D with C++ or Python?


I am struggling to create and apply basic texture in Qt. I am trying to use QDiffuseSpecularMaterial Class but its maps are of QVariant type. I suppose I should use QAbstractTexture Class to load the textures and then convert them to QVariant somehow. Problem is that QAbstractTexture Class doesn't have any method that loads the texture. There is an addTextureImage method but its argument is QAbstractTextureImage Class that still doesn't have any load method. Even if I could load the textures somehow I have no idea how to convert them to QVariant. Does anyone know how to create and apply any basic image to the any basic 3D object? Is it possible to use QImage or QPixmap and convert them to Textures or QVariant somehow?


Solution

  • You were on the right track. The QVariants of QDiffuseSpecularMaterial are either a plain color or a texture, according to the docs.

    Now, if you want to provide a texture, you have to use QTexture2D (I assume you want to provide a 2D image) which inherits from QAbstractTexture. To actually make QTexture2D use your textures, you have to use addTextureImage (a function defined in QAbstractTexture). addTextureImage accepts QAbstractTextureImages. The classes QPaintedTextureImage and QTextureImage both inhert from QAbstractTextureImage - using the former, you can manually paint a texture using QPainter, using the latter you can provide the URL to your texture file.

    This is an example from a project I forked:

    Entity {
        id: root
    
        Texture2D{
            id: texture
            TextureImage {
                source: "qrc:/man.png"
            }
        }
    
        RenderableEntity{
            id: chest
            source: "qrc:/man.obj"
    
            material: DiffuseMapMaterial {
                id: material
                diffuse:  texture
                specular: Qt.rgba( 0.2, 0.2, 0.2, 1.0 )
                shininess: 2.0
            }
        }
    }