C++ 将qwidget上的当前项目另存为图像

C++ 将qwidget上的当前项目另存为图像,c++,qt,qt4,C++,Qt,Qt4,我正在尝试在QWidget中用随机颜色绘制一些菱形。我想将当前的QWidget保存为图像。我使用这样的代码来实现这一点: 问题是,render()似乎再次调用了paintEvent,而paintEvent将使用新的随机颜色绘制菱形,因此,与显示的图像相比,保存的图像总是不同的。有人能告诉我如何保存当前的QWidget?提前谢谢 绘制菱形的代码: 无效对话框::paintEvent(QPaintEvent*e){ QPainter painter(本); QRect背景(0,0,此->几何体().

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

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

绘制菱形的代码:

无效对话框::paintEvent(QPaintEvent*e){

QPainter painter(本);
QRect背景(0,0,此->几何体().width(),此->几何体().height());
画师:挫折(QBrush(Qt::白色));
painter.setPen(Qt::NoPen);
//QBrush bbrush(Qt::黑色,Qt::SolidPattern);
画家drawRect(背景);
int width=this->geometry().width();
int height=this->geometry().height();
//画矩形
int rec_size=64;
int行=0;
int cols=0;
行数=地板((双倍)高度/(双倍)rec_尺寸);
cols=地板((双)宽度/(双)rec_尺寸);
QPointF points[4];//QRect rec(0,0,rec_size,rec_size);

对于(int i=0;i,您可以使用布尔类型的类成员变量在
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;

正确:绘制所需的图像,并在绘制事件中绘制图像。
void Dialog::paintEvent(QPaintEvent *e) {

   ...

   if(isRandom)
   {
       lastColor = rand() % color_size;
       painter.setBrush( QBrush( colors[lastColor] ) );
    }
    else
       painter.setBrush( QBrush( colors[lastColor] ) );

    ...

}
isRandom = false;

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

isRandom = true;