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?

Qt Code:
  1. import os , sys , time
  2. from PyQt5 import QtWidgets
  3. from PyQt5.QtWidgets import *
  4. from PyQt5.QtGui import *
  5. from PyQt5.QtCore import *
  6. import numpy as np
  7.  
  8. class MyApp(QWidget):
  9.  
  10. def __init__(self):
  11. super().__init__()
  12. self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)
  13. self.setAttribute(Qt.WA_TranslucentBackground)
  14. self.initUI()
  15.  
  16. def initUI(self):
  17. self.setGeometry(30, 30, 300, 300)
  18. self.setWindowTitle('blRect')
  19. self.show()
  20.  
  21. def screenshot(self):
  22. self.preview_screen = QApplication.primaryScreen().grabWindow(self.winId() )
  23. self.preview_screen.save('test.jpg', "jpg")
  24.  
  25. def paintEvent(self, e):
  26. qp = QPainter()
  27. qp.begin(self)
  28. self.draw_rect(qp)
  29. self.screenshot()
  30. qp.end()
  31.  
  32. def draw_rect(self, qp):
  33. qp.setBrush(QColor(255, 255, 0))
  34. qp.setPen(QPen(QColor(0, 0, 0), -1))
  35. qp.setBrush(QColor(0, 0, 0))
  36. # print(self.width() , self.height())
  37. for i in range(3):
  38. rand_x = 100 * np.random.randn()
  39. rand_y = 100 * np.random.randn()
  40. qp.drawRect(self.width() /2 + rand_x, self.height() / 2 + rand_y, 100, 20)
  41.  
  42. def main():
  43. app = QApplication(sys.argv)
  44. ex = MyApp()
  45. sys.exit(app.exec_())
  46.  
  47. if __name__ == '__main__':
  48. main()
To copy to clipboard, switch view to plain text mode