user7825011
user7825011

Reputation: 43

QPaintedTextureImage in Qt3D (Qt 5.8)

I want to create an entity with Qt3D that has a custom image as texture. I came across the QPaintedTextureImage (link leads to Qt 5.9 version for details. Here ist doc for 5.8), which can be written with a QPainter but I don't understand how. First, this is how I imagine the entity could look like:

[EDIT]: code is edited and works now!

planeEntity = new Qt3DCore::QEntity(rootEntity);

planeMesh = new Qt3DExtras::QPlaneMesh;
planeMesh->setWidth(2);
planeMesh->setHeight(2);

image = new TextureImage; //see below
image->setSize(QSize(100,100));
painter = new QPainter; 
image->paint(painter)  

planeMaterial = new Qt3DExtras::QDiffuseMapMaterial; 
planeMaterial->diffuse()->addTextureImage(image);

planeEntity->addComponent(planeMesh);
planeEntity->addComponent(planeMaterial);

TextureImage is the subclassed QPaintedTextureImage with paint function:

class TextureImage : public Qt3DRender::QPaintedTextureImage
{
public:    
    void paint(QPainter* painter);
};

What does the QPainter, passed to paint function, need to do in the implementation of paint if I just want to draw a big circle to the planeEntity?

[Edit] Implementation:

void TextureImage::paint(QPainter* painter)
{ 
  //hardcoded values because there was no device()->width/heigth
  painter->fillRect(0, 0, 100, 100, QColor(255, 255, 255));

  /* Set pen and brush to whatever you want. */
  painter->setPen(QPen(QBrush(QColor(255, 0, 255)) ,10));
  painter->setBrush(QColor(0, 0, 255));

  /*
   * Draw a circle (or an ellipse -- the outcome depends very much on
   * the aspect ratio of the bounding rectangle amongst other things).
   */
  painter->drawEllipse(0, 0, 100, 100);
}

Upvotes: 2

Views: 1134

Answers (2)

Basile Perrenoud
Basile Perrenoud

Reputation: 4112

It might be simpler to dynamically load the image you need in QML. I had to do it not so long ago and opened a question on SO for it:

Qt3D dynamic texture

Upvotes: 0

G.M.
G.M.

Reputation: 12899

The short answer is... use QPainter exactly the same way you would normally.

void TextureImage::paint (QPainter* painter)
{
  int w = painter->device()->width();
  int h = painter->device()->height();

  /* Clear to white. */
  painter->fillRect(0, 0, w, h, QColor(255, 255, 255));

  /* Set pen and brush to whatever you want. */
  painter->setPen(QPen(QBrush(QColor(0, 0, 0)) ,10));
  painter->setBrush(QColor(0, 0, 255));

  /*
   * Draw a circle (or an ellipse -- the outcome depends very much on
   * the aspect ratio of the bounding rectangle amongst other things).
   */
  painter->drawEllipse(0, 0, w, h);
}

However, note that you really shouldn't invoke the paint method directly. Instead use update which will cause Qt to schedule a repaint, initialize a QPainter and invoke your overridden paint method with a pointer to that painter.

Upvotes: 3

Related Questions