Reputation: 181
i want to draw some rhombuses in a qwidget and save it as image automatically. I use the following code in the paintEvent and get this error "QWidget::repaint: Recursive repaint detected". Problem is that render() seems to call the paintEvent() again, I always get stuck in an infinite, recursive paintEvent call. Is there any way to save the qwidget automatically after drawing. Any advices would be grateful.
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();
int rec_size=64;
int rows=floor((double)height/(double)rec_size);
int cols=floor((double)width/(double)rec_size);
QPointF points[4];
for (int i=0;i<floor(rows);i++){
for (int j=0;j<floor(cols);j++){
painter.setBrush( QBrush( colors[rand() % color_size] ) );
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);
}
}
QPixmap pixmap(this->size());
this->render(&pixmap);
pixmap.save("test.png");
}
Upvotes: 3
Views: 3250
Reputation: 364
Call render() outside of paintevent(), render will repaint widget and save it to pixmap or am i missing something?
If you need to catch paint event itself, then use QObject::installEventFilter() or QObject::event() routines.
Upvotes: 0
Reputation: 10959
You can have boolean variable as a member in widget. It will control calling render function or not. So you can avoid infinite recursion.
m_callRender
is the member variable. If paintEvent
is called as a result of render
function, render
will not called again.
paintevent
{
... // drawing part
if (m_callRender) {
m_callRender = false;
QPixmap pixmap(this->size());
this->render(&pixmap);
pixmap.save("test.png");
m_callRender = true;
}
}
Upvotes: 3