Home > database >  How to save a gui created with qt and python as an image
How to save a gui created with qt and python as an image

Time:04-02

I am trying to use qt creator and python to generate flowcharts with values. I want to save the generated flowchart as an image after, but I cannot figure out how to do it. Here is my attempt:

import sys
from PyQt5 import QtWidgets, uic
from PyQt5.QtGui import *

from mainwindow import Ui_MainWindow


class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, *args, obj=None, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.setupUi(self)


app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
screen = app.primaryScreen()
screenshot = screen.grabWindow(window)
screen.save('screenshot.png', 'png')

CodePudding user response:

The fact that the show method is called does not imply that it is shown instantly, but rather that this method notifies the OS so that the window is created. A possible solution is to use a QTimer, on the other hand the grabWindow method grabs a window using the associated WID, in this case it is better to use the grab method:

from functools import partial


def take_screenshot(widget):
    pixmap = widget.grab()
    if not pixmap.isNull():
        pixmap.save("/fullpath/of/screenshot.png", "PNG")
    QApplication.quit()


def main():
    app = QtWidgets.QApplication(sys.argv)

    window = MainWindow()
    window.show()

    QTimer.singleShot(500, partial(take_screenshot, window))

    app.exec_()


if __name__ == "__main__":
    main()
  • Related