Search code examples
c++qtqwidgetqpainterqabstractbutton

Paint device returned engine == 0, type: 1


I have seen many answers for the same Question, I have already gone through them but none them solved my problem, I am getting the error

QWidget::paintEngine: Should no longer be called QPainter::begin: Paint device returned engine == 0, type: 1 QPainter::end: Painter not active, aborted

I need to know, What is type : 1, and why this error showing,

My code is

iconwidget.h

class IconWigdet : public QAbstractButton
{
Q_OBJECT
QRect *iconarea;
QPainter p;
QPixmap *icon; 
public:
explicit IconWigdet(QRect *rectangle,QPixmap *tempicon);
void paintEvent(QPaintEvent *);  
};

iconwidget.cpp

IconWigdet::IconWigdet(QRect *rectangle,QPixmap *tempicon)
{
iconarea = new QRect();
*iconarea = *rectangle  ;
icon = new QPixmap(*tempicon);
this->setGeometry(0,0,iconarea->width(),iconarea->height()+20);
}

void IconWigdet::paintEvent(QPaintEvent *)
{
qDebug() << " PaintEvent ";
p.begin(this);
p.drawText(iconarea->x()+ 10,iconarea->height()+10, "name");
p.drawPixmap ( *iconarea,*icon );
p.end();
}

groupwidget.h

class GroupWidget: public QWidget
{
Q_OBJECT
QGridLayout *groupLayout = new QGridLayout ;
QRect *rect = new QRect( 0, 0, 100, 100);
QPixmap *pimap = new QPixmap("../widgeticon/icons/ball.png");
IconWigdet *icon = new IconWigdet(rect,pimap);
public:
GroupWidget();
};

groupwidget.cpp

GroupWidget::GroupWidget()
{ 
groupLayout->addWidget(icon, 0, 1, 1, 1, 0);
this->setLayout(groupLayout);
icon->show();
QPaintEvent *e;
icon->paintEvent(e);
}

main.cpp

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
GroupWidget *Gw = new GroupWidget;
Gw->show();
return a.exec();
}

and the iconwidget class will work perfectly if the main function changed to

int main(int argc, char *argv[])
{
QApplication a(argc, argv);;   
QRect *rect = new QRect( 0, 0, 100, 100);
QPixmap *pimap = new QPixmap("../widgeticon/icons/ball.png");
IconWigdet *Iw = new IconWigdet(rect,pimap);
Iw->show();
return a.exec();
}

that means, If we use iconwidget class object in main function it is working, but it is not working when we do the same in groupwidget class,

Thanks in advance


Solution

  • You're calling IconWigdet::paintEvent directly. This is not allowed. Instead of calling it directly, call QWidget::update or QWidget::repaint.

    GroupWidget::GroupWidget()
    { 
        groupLayout->addWidget(icon, 0, 1, 1, 1, 0);
        this->setLayout(groupLayout);
        icon->show();
        // QPaintEvent *e;
        // icon->paintEvent(e); this is not allowed
        icon->update(); // do this instead
    }
    

    Though I don't see why would you call anything there. Just calling Icon->show(); should be enough. Qt will automatically schedule a paint event.