Qt使用双缓冲绘图时报错:pure virtual method called

这个问题折磨了我将近四个小时。

起始原因是想写一个双缓冲绘图的画板,大概看了一下网上的教程,理解双缓冲绘图的思想后,没有完全参照网上的步骤,想着用自己的思路实现一下。(其实和网上的教程也没有太大差别)

然后就出现问题了,出现问题的关键的代码如下:

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();
    }

  

 

转载于:https://www.cnblogs.com/XiaoXiaoShuai-/p/10822814.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值