Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyQt4 - QWidget save as image

Tags:

python

pyqt4

I'm trying to use Python to programmatically save a QWidget in PyQt4 as an image (any format would be fine - PNG, PDF, JPEF, GIF...etc)

I thought this would be very straightforward, but I actually wasn't able to find anything on the web about it. Can someone point me in the right direction?

To be clear, I'm trying to do this

gui = <SOME QMainWindow>
gui.show()  # this displays the gui. it's useful, but what i need is to save the image
gui.save("image.png")    ## How do I do this?  
like image 695
user3240688 Avatar asked Jan 11 '23 08:01

user3240688


1 Answers

You can do this using the QPixmap.grabWindow() method.

From the docs:

Grabs the contents of the window window and makes a pixmap out of it. Returns the pixmap.

The arguments (x, y) specify the offset in the window, whereas (w, h) specify the width and height of the area to be copied.

If w is negative, the function copies everything to the right border of the window. If h is negative, the function copies everything to the bottom of the window.

Note that grabWindow() grabs pixels from the screen, not from the window. If there is another window partially or entirely over the one you grab, you get pixels from the overlying window, too.

Note also that the mouse cursor is generally not grabbed.

The reason we use a window identifier and not a QWidget is to enable grabbing of windows that are not part of the application, window system frames, and so on.

Warning: Grabbing an area outside the screen is not safe in general. This depends on the underlying window system.

Warning: X11 only: If window is not the same depth as the root window and another window partially or entirely obscures the one you grab, you will not get pixels from the overlying window. The contests of the obscured areas in the pixmap are undefined and uninitialized.

Sample code:

import sys
from PyQt4.QtGui import *

filename = 'Screenshot.jpg'
app = QApplication(sys.argv)
widget = QWidget()
widget.setLayout(QVBoxLayout())
label = QLabel()
widget.layout().addWidget(label)

def take_screenshot():
    p = QPixmap.grabWindow(widget.winId())
    p.save(filename, 'jpg')

widget.layout().addWidget(QPushButton('take screenshot', clicked=take_screenshot))

widget.show()
app.exec_()

This will produce a window that looks like this:

Application UI

When you click the button, it will create a file named Screenshot.jpg in the current directory. Said image will look like this (notice the window frame is missing):

Screenshot

like image 157
Andy Avatar answered Jan 19 '23 10:01

Andy