If the background is transparent, PrimaryScreen().grabWindow(self.winId()) Question.
I'm trying to use the primaryScreen().grabWindow(self.winId() to implement a screenshot, but when the background is not clear, the screenshot is good.
If the background is transparent, the stored image is saved as a black image. Why is this happening?
Code:
import os , sys , time
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import numpy as np
def __init__(self):
super().__init__()
self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)
self.setAttribute(Qt.WA_TranslucentBackground)
self.initUI()
def initUI(self):
self.setGeometry(30, 30, 300, 300)
self.setWindowTitle('blRect')
self.show()
def screenshot(self):
self.
preview_screen = QApplication.
primaryScreen().
grabWindow(self.
winId() ) self.preview_screen.save('test.jpg', "jpg")
def paintEvent(self, e):
qp.begin(self)
self.draw_rect(qp)
self.screenshot()
qp.end()
def draw_rect(self, qp):
qp.
setBrush(QColor(255,
255,
0)) # print(self.width() , self.height())
for i in range(3):
rand_x = 100 * np.random.randn()
rand_y = 100 * np.random.randn()
qp.drawRect(self.width() /2 + rand_x, self.height() / 2 + rand_y, 100, 20)
def main():
ex = MyApp()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Re: If the background is transparent, PrimaryScreen().grabWindow(self.winId()) Questi
Quote:
Originally Posted by
yskioi
I'm trying to use the primaryScreen().grabWindow(self.winId() to implement a screenshot, but when the background is not clear, the screenshot is good.
If the background is transparent, the stored image is saved as a black image. Why is this happening?
The translucent area of your widget's client area is all black with a zero alpha channel. You save as JPEG, which has no alpha channel, and therefore the result is a solid black background with black boxes drawn on top. If you save as PNG, which has alpha channel support, then you get a transparent image with black boxes draw on top.
None of the content you can see through the translucent background is part of your widget's content, so it is not captured. You see it on screen because your window manager (whatever platform) is composing your widget with what lies behind (On KDE toggle compositing with Shift-Alt-F12, maybe switch off Aero on Windows?). It is the relevant portion of the composed screen buffer you need to be accessing.
Have a look at Spectacle for an example of how you might do this on X11 systems.
Maybe Lightscreen on Windows.
QScreen::grabWindow() is probably useful.