How to use QPainter on QPixmap

寵の児 提交于 2019-12-18 14:52:18

问题


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();
}

回答1:


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
...



回答2:


QPixmap should be created without new keyword. It's usually passed by value or reference, not by pointer. One of the reasons is that QPixmap is not capable of tracking its changes. When you add a pixmap to a scene using addPixmap, only the current pixmap is used. Further changes will not affect the scene. So you should call addPixmap after you make changes.

Also you need to destroy QPainter before you use the pixmap to ensure that all changes will be written to the pixmap and to avoid memory leak.

QPixmap pix(500,500);
QPainter *paint = new QPainter(&pix);
paint->setPen(QColor(255,34,255,255));
paint->drawRect(15,15,100,100);
delete paint;
scene->addPixmap(pix);


来源:https://stackoverflow.com/questions/17888795/how-to-use-qpainter-on-qpixmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!