Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use QPainter on QPixmap

I'm a newbie to Qt/Embedded. I want to use QPainter to draw stuff on a QPixmap, which will be added to QGraphicsScene. Here is my code. But it does not show the drawings on the pixmap. It shows only the black pixmap.

int main(int argc, char **argv) {

  QApplication a(argc, argv);

  QMainWindow *win1 = new QMainWindow();
  win1->resize(500,500);
  win1->show();


  QGraphicsScene *scene = new QGraphicsScene(win1);
  QGraphicsView view(scene, win1);
  view.show();
  view.resize(500,500);

  QPixmap *pix = new QPixmap(500,500);
  scene->addPixmap(*pix);

  QPainter *paint = new QPainter(pix);
  paint->setPen(*(new QColor(255,34,255,255)));
  paint->drawRect(15,15,100,100);

  return a.exec();
}
like image 428
random.cs.guy Avatar asked Jul 26 '13 18:07

random.cs.guy


People also ask

How do you draw an arc in Qt?

QPointF O; // intersection of lines QPointF B; // end point of horizontal line QPointF A; // end point of other line float halfSide = B.x-O.x; QRectF rectangle(O.x - halfSide, O.y - halfSide, O.x + halfSide, O.y + halfSide); int startAngle = 0; int spanAngle = (atan2(A.y-O.y,A.x-O.x) * 180 / M_PI) * 16; QPainter ...


1 Answers

You need to do the painting on the bitmap before you add it to the scene. When you add it to the scene, the scene will use it to construct a QGraphicsPixmapItem object, which is also returned by the addPixmap() function. If you want to update the pixmap after it has been added, you need to call the setPixmap() function of the returned QGraphicsPixmapItem object.

So either:

...
QPixmap *pix = new QPixmap(500,500);
QPainter *paint = new QPainter(pix);
paint->setPen(*(new QColor(255,34,255,255)));
paint->drawRect(15,15,100,100);
scene->addPixmap(*pix); // Moved this line
...

or:

...
QPixmap *pix = new QPixmap(500,500);
QGraphicsPixmapItem* item(scene->addPixmap(*pix)); // Save the returned item
QPainter *paint = new QPainter(pix);
paint->setPen(*(new QColor(255,34,255,255)));
paint->drawRect(15,15,100,100);
item->setPixmap(*pix); // Added this line
...
like image 91
Daniel Hedberg Avatar answered Sep 30 '22 20:09

Daniel Hedberg