How to use QPainter in QPixmap

I am new to Qt / Embedded. I want to use QPainter to draw material on a QPixmap , which will be added to QGraphicsScene . Here is my code. But he does not show drawings on pixmap. It shows only 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(); } 
+8
qt qt4 qpixmap qpainter qgraphicsscene
source share
2 answers

You need to draw a picture on the bitmap before to add it to the scene. When you add it to the scene, the scene will use it to create the QGraphicsPixmapItem object, which is also returned by the addPixmap() function. If you want to update pixmap after adding it, 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 ... 
+12
source share

QPixmap must be created without the new keyword. It is usually passed by value or reference, and not by pointer. One reason is that QPixmap not able to track changes. When you add pixmap to the scene using addPixmap , only the current pixmap is used. Further changes will not affect the scene. Therefore, you must call addPixmap after making the change.

You also need to destroy QPainter before using pixmap to ensure that all changes are written to pixmap and avoid memory leaks.

 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); 
+8
source share

All Articles