将qwidget上的当前项目保存为图像

save the current items on qwidget as image

本文关键字:项目 保存 图像 qwidget      更新时间:2023-10-16

我试图在QWidget中绘制一些随机颜色的菱形。我想把当前的QWidget保存为图像。我使用这样的代码:

QPixmap pixmap(this->size());
this->render(&pixmap);
pixmap.save("test.png");

问题是render()似乎再次调用paintEvent, paintEvent将用新的随机颜色绘制菱形,这样我总是得到与显示的图像相比保存的不同图像。有人能告诉我如何保存当前的QWidget吗?提前谢谢。

绘制菱形的代码:

void Dialog::paintEvent(QPaintEvent *e) {

QPainter painter(this);
QRect background(0,0,this->geometry().width(),this->geometry().height());
painter.setBrush( QBrush( Qt::white ) );
painter.setPen( Qt::NoPen );
//QBrush bbrush(Qt::black,Qt::SolidPattern);
painter.drawRect(background);
int width = this->geometry().width();
int height = this->geometry().height();
//draw rectangles
int rec_size=64;
int rows=0;
int cols=0;
rows=floor((double)height/(double)rec_size);
cols=floor((double)width/(double)rec_size);
QPointF points[4]; //    QRect rec(0,0,rec_size,rec_size);
for (int i=0;i<floor(rows);i++){
    for (int j=0;j<floor(cols);j++){
       painter.setBrush( QBrush( colors[rand() % color_size] ) );
     
       //QPainter painter(this);
       points[0] = QPointF(rec_size*(j),rec_size*(i+0.5));
       points[1] = QPointF(rec_size*(j+0.5),rec_size*(i));
       points[2] = QPointF(rec_size*(j+1),rec_size*(i+0.5));
       points[3] = QPointF(rec_size*(j+0.5),rec_size*(i+1));
       painter.drawPolygon(points, 4);
    }
}
painter.end();

}

您可以使用布尔类型的类成员变量来检查paintEvent中是否应该使用随机颜色。还需要一个变量来保存最后使用的颜色的索引:

bool isRandom;
int lastColor;

paintEvent应该是:

void Dialog::paintEvent(QPaintEvent *e) {
   ...
   if(isRandom)
   {
       lastColor = rand() % color_size;
       painter.setBrush( QBrush( colors[lastColor] ) );
    }
    else
       painter.setBrush( QBrush( colors[lastColor] ) );
    ...
}

当定期绘制小部件时,该变量为true。当你想保存它的图像时,将变量赋值为false,保存图像并再次赋值为true:

isRandom = false;
QPixmap pixmap(this->size());
this->render(&pixmap);
pixmap.save("test.png");
isRandom = true;