如何在QPixmap上使用QPainter

Cra*_*008 13 qt qt4 qpixmap qpainter qgraphicsscene

我是Qt/Embedded的新手.我想用它QPainter来绘制一个东西QPixmap,它将被添加到QGraphicsScene.这是我的代码.但它没有在像素图上显示图纸.它只显示黑色像素图.

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();
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*erg 17

在将位图添加到场景之前,您需要在位图上进行绘制.将它添加到场景时,场景将使用它来构造一个QGraphicsPixmapItem对象,该对象也由addPixmap()函数返回.如果要在添加pixmap后更新pixmap,则需要调用setPixmap()返回QGraphicsPixmapItem对象的函数.

所以要么:

...
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
...
Run Code Online (Sandbox Code Playgroud)

要么:

...
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
...
Run Code Online (Sandbox Code Playgroud)


Pav*_*hov 11

QPixmap应该创建没有new关键字.它通常通过值或引用传递,而不是通过指针传递.其中一个原因是QPixmap无法跟踪其变化.使用像素图添加到场景时addPixmap,仅使用当前像素图.进一步的改变不会影响现场.因此,您应该addPixmap在进行更改后致电.

此外,您需要QPainter在使用像素图之前销毁,以确保所有更改都将写入像素图并避免内存泄漏.

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);
Run Code Online (Sandbox Code Playgroud)