Search code examples
pythonscreenshotpyside

how to take a screenshot of a PySide widget that is a window, and include the titlebar and border


I figured out how to take a screen capture of a widget in PySide QT, but it doesn't include nonclient areas e.g. the titlebar and border.

def screenCaptureWidget(widget, filename, fileformat='png'):
    pixmap =  QtGui.QPixmap.grabWidget(widget)
    pixmap.save(filename, fileformat)

Two questions:

  • how do I include the nonclient areas?
  • how do I get the geometry of the window rectangle relative to its client area (0,0) point?

Solution

  • I think I figured out the answer to both questions, after finding QWidget.geometry() and QWidget.frameGeometry(), which give screen coordinates (as a QRect) of the client and nonclient areas, respectively.

    def getRelativeFrameGeometry(widget):
        g = widget.geometry()
        fg = widget.frameGeometry()
        return fg.translated(-g.left(),-g.top())
    
    def screenCaptureWidget(widget, filename, fileformat='png'):
        rfg = getRelativeFrameGeometry(widget)
        pixmap =  QtGui.QPixmap.grabWindow(widget.winId(),
                                           rfg.left(), rfg.top(),
                                           rfg.width(), rfg.height())
        pixmap.save(filename, fileformat)