我想在整个屏幕上绘制一个具有透明背景的图像。 我之前用Xlib完成过类似的操作,但是为了让我的程序可以在不同的环境中工作,我决定尝试使用Qt。 在做出决定之前,我曾经在网上搜索过现成的示例,但是未能找到可行的。
所以,我有一张带有透明背景的PNG格式的坐标图像需要叠加在屏幕上。 下面是我想看到的效果,我的桌面上覆盖着坐标图像:
这是我的PyQt6代码,它可以将图像画满全屏,但是遗憾的是你无法透过图像看到背景,因为它有黑色的背景:
import sys
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QImage
from PyQt6.QtWidgets import QApplication, QMainWindow
from PyQt6.QtGui import QPainter
class Img(QMainWindow):
def __init__(self, img_path, parent=None):
super().__init__(parent)
self.qimg = QImage(img_path)
self.setStyleSheet('QMainWindow {background:transparent}')
self.setWindowFlags(
Qt.WindowType.WindowStaysOnTopHint |
Qt.WindowType.FramelessWindowHint |
Qt.WindowType.WindowTransparentForInput
)
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
def paintEvent(self, qpaint_event):
painter = QPainter(self)
rect = qpaint_event.rect()
painter.drawImage(rect, self.qimg)
self.showFullScreen()
if __name__ == "__main__":
app = QApplication(sys.argv)
img_path = 'coords.png'
window = Img(img_path)
window.show()
sys.exit(app.exec())
答案不一定要是PyQt6,也可以是PyQt5或用Go编写。