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?
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:
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):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With