使用Qt在屏幕上绘制透明图像

8

我想在整个屏幕上绘制一个具有透明背景的图像。 我之前用Xlib完成过类似的操作,但是为了让我的程序可以在不同的环境中工作,我决定尝试使用Qt。 在做出决定之前,我曾经在网上搜索过现成的示例,但是未能找到可行的。

所以,我有一张带有透明背景的PNG格式的坐标图像需要叠加在屏幕上。 下面是我想看到的效果,我的桌面上覆盖着坐标图像: enter image description here

这是我的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编写。


1
你能进一步解释一下问题吗?我不明白你想要实现什么,当我运行程序时,我得到一个覆盖所有内容的图像窗口,这显然是你想要的,对吧? - WhoKnowsMe
@WhoKnowsMe 我已经重新撰写了我的问题,重要的是我的图片有透明部分,你应该能够通过它们看到你的桌面。你可以吗?谢谢。 - GGG
1个回答

4
我已经尝试了你的代码,它运行良好,显然似乎是图像的问题,我建议使用一些外部应用程序来擦除透明部分,例如这个
这里有一个测试可以使用您的代码:enter image description here 如果您想要自动完成此操作,建议使用opencv。

2
谢谢,知道了这个问题后我想一定是我的窗口管理器(bspwm)的问题,于是我安装并运行了一个合成器(picom),现在它可以正常工作了 :) - GGG
2
我会查看opencv。 - GGG
2
我建议您查看这个SO问题这个GeeksforGeeks的问题 - WhoKnowsMe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接