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

文章目录

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

1 问题重现

QPainter::begin: Painter already active问题解决方案_第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 active
        painter.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);//194
        painter.drawLine(60, 452, 1006, 452);//392
        painter.drawLine(60, 648, 1006, 648);//588
        painter.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();
    }
}

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 active
        painter.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);//194
        painter.drawLine(60, 452, 1006, 452);//392
        painter.drawLine(60, 648, 1006, 648);//588
        painter.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();
    }
}

你可能感兴趣的:(Qt,QPainter,Qt)