Problem when Capturing Screen of Web Page using QWebView

The following code can print the current web page to an image.

page()->setViewportSize(page()->mainFrame()->contentsSize());
QImage *image=new QImage(page()->mainFrame()->contentsSize(), QImage::Format_ARGB32);
QPainter *painter = new QPainter(image);
page()->mainFrame()->render(painter);
image->save(QString("images/%1.png").arg(name));

 

However there are some issues needed to mention. First, contentsSize() may return an invalid size you need to validate. Otherwise, the QImage object would be null and you will get the following errors:

QPainter::begin: Paint device returned engine == 0, type: 3
QPainter::setRenderhint: Painter must be active to set rendering hints
QPainter::setBrush: Painter not active
QPainter::pen Painter not active
QPainter::setPen: Painter not active
QImage::scaleWidth: Image is a null image
QPainter::restore: Unbalanced save/restore

How to check if image is null? You cannot use the statement “if(image==NULL)” to do this, but should use “if(image.isNull())” as image is not NULL in almost cases even the image is not valid.

Another issue is that you should not resize the QWebView when taking the screenshot of the web page, otherwise the program would crash or freeze.

Posted in

Comments are closed, but trackbacks and pingbacks are open.