这个问题折磨了我将近四个小时。
起始原因是想写一个双缓冲绘图的画板,大概看了一下网上的教程,理解双缓冲绘图的思想后,没有完全参照网上的步骤,想着用自己的思路实现一下。(其实和网上的教程也没有太大差别)
然后就出现问题了,出现问题的关键的代码如下:
void MainWindow::Paint()
{
if(curShape == none)
return;
int x1 = lastPoint.x();
int y1 = lastPoint.y();
int w = endPoint.x() - x1;
int h = endPoint.y() - y1;
QPainter painter(&image);
tempImage = image.copy();
QPainter tempPainter(&tempImage);
switch (curShape) {
case randomLine:
painter.drawLine(lastPoint,endPoint);
lastPoint = endPoint;
break;
case line:
tempPainter.drawLine(lastPoint,endPoint);
break;
case rectangle:
tempPainter.drawRect(x1,y1,w,h);
default:
break;
}
if(!isDrawing)
{
image = tempImage.copy();
}
update();
}
在调试时,跳转到了这个地方:
QPainter::~QPainter()
{
d_ptr->inDestructor = true;
QT_TRY {
if (isActive())
end();
else if (d_ptr->refcount > 1)
d_ptr->detachPainterPrivate(this);
} QT_CATCH(...) {
// don't throw anything in the destructor.
}
if (d_ptr) {
// Make sure we haven't messed things up.
Q_ASSERT(d_ptr->inDestructor);
d_ptr->inDestructor = false;
Q_ASSERT(d_ptr->refcount == 1);
if (d_ptr->d_ptrs)
free(d_ptr->d_ptrs);
}
}
哎,感觉自己傻逼,IDE都告诉我是painter析构时出现问题了,可是我却还是在其他地方找错误,甚至把自己的代码改成和网上的一样的(能运行成功),但是我却偏不信邪,偏要用自己的思路!
最终,发现了问题的所有,问题出在这个地方:
if(!isDrawing)
{
image = tempImage.copy();
}
因为我将image强行初始化了,导致寄托在image上的painter没有析构成功。
解决方法很简单,在将image初始化之前将painter显式析构一下就可以了。
if(!isDrawing)
{
painter.~QPainter();
image = tempImage.copy();
}