当前位置: 代码迷 >> 综合 >> QPainter::begin: Painter already active问题解决方案
  详细解决方案

QPainter::begin: Painter already active问题解决方案

热度:20   发布时间:2024-01-29 08:20:39.0

文章目录

  • 1 问题重现
  • 2 原因
  • 3 解决方法

1 问题重现

在这里插入图片描述

2 原因

重新实现paintEvent函数时,如果使用QPainter painter(this);,再使用begin、end则会重复包含QPainter。官方给出的主意事项:

Note that most of the time, you can use one of the constructors instead of begin(), and that end() is automatically done at destruction.Warning: A paint device can only be painted by one painter at a time.

void ShowImage::paintEvent(QPaintEvent *event)
{if(ui->stackedWidget->currentIndex() == 0){QPainter painter(this);/painter.begin(this);//会出现QPainter::begin: Painter already activepainter.setPen(QPen(Qt::blue, 2, Qt::SolidLine, Qt::RoundCap));painter.drawLine(0, 28, this->width(), 28);painter.drawLine(1006, 28, 1006, this->height());painter.setPen(QPen(Qt::red, 2, Qt::SolidLine, Qt::RoundCap));painter.drawLine(60, 254, 1006, 254);//194painter.drawLine(60, 452, 1006, 452);//392painter.drawLine(60, 648, 1006, 648);//588painter.drawLine(60, 844, 1006, 844);//painter.end();}else if(ui->stackedWidget->currentIndex() == 1){QPainter painter(this);painter.begin(this);painter.setPen(QPen(Qt::blue, 2, Qt::SolidLine, Qt::RoundCap));painter.drawLine(0, 28, this->width(), 28);painter.drawLine(1006, 28, 1006, this->height());//1030painter.end();}
}

3 解决方法

在使用QPainter painter(this)时,不使用begin和end

void ShowImage::paintEvent(QPaintEvent *event)
{if(ui->stackedWidget->currentIndex() == 0){QPainter painter(this);// painter.begin(this);//会出现QPainter::begin: Painter already activepainter.setPen(QPen(Qt::blue, 2, Qt::SolidLine, Qt::RoundCap));painter.drawLine(0, 28, this->width(), 28);painter.drawLine(1006, 28, 1006, this->height());painter.setPen(QPen(Qt::red, 2, Qt::SolidLine, Qt::RoundCap));painter.drawLine(60, 254, 1006, 254);//194painter.drawLine(60, 452, 1006, 452);//392painter.drawLine(60, 648, 1006, 648);//588painter.drawLine(60, 844, 1006, 844);////painter.end();}else if(ui->stackedWidget->currentIndex() == 1){QPainter painter(this);//painter.begin(this);painter.setPen(QPen(Qt::blue, 2, Qt::SolidLine, Qt::RoundCap));painter.drawLine(0, 28, this->width(), 28);painter.drawLine(1006, 28, 1006, this->height());//1030// painter.end();}
}
  相关解决方案