所以我试图拥有一个既可交互又透明的背景。我希望能够在屏幕上绘图。如下面的视频所示,如果我使用 self.background.fill(Qt.transparent)
,背景不会像预期的那样透明,而是黑色。但是当我使用 self.setAttribute(Qt.WA_TranslucentBackground)
时,我根本无法绘制,它只是与它下面的窗口进行交互。如何制作一个透明的窗口,同时还能在上面绘图?
正如所见,self.setStyleSheet("background: transparent;")
也什么都不做。背景还是黑色的
这是我的代码:
import sys
from PyQt5.QtCore import QPoint, Qt
from PyQt5.QtGui import QPainter, QPen, QPixmap
from PyQt5.QtWidgets import QApplication, QMainWindow
from screeninfo import get_monitors
class Canvas(QMainWindow):
def __init__(self):
super().__init__()
self.drawing = False
self.lastPoint = QPoint()
self.initUI()
def initUI(self):
monitor = get_monitors()[0]
self.setStyleSheet("background: transparent;")
self.background = QPixmap(monitor.width, monitor.height)
self.background.fill(Qt.transparent)
self.setGeometry(0, 0, 1920, 1080)
self.resize(monitor.width, monitor.height)
# self.setWindowOpacity(0.5)
self.setWindowFlags(Qt.Window | Qt.CustomizeWindowHint | Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
self.setAttribute(Qt.WA_TranslucentBackground)
def paintEvent(self, event):
painter = QPainter(self)
painter.drawPixmap(self.rect(), self.background)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.drawing = True
self.lastPoint = event.pos()
def mouseMoveEvent(self, event):
if event.buttons() and Qt.LeftButton and self.drawing:
painter = QPainter(self.background)
painter.setPen(QPen(Qt.magenta, 5, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
# print(self.lastPoint, event.pos())
painter.drawLine(self.lastPoint, event.pos())
self.lastPoint = event.pos()
self.update()
def mouseReleaseEvent(self, event):
if event.button == Qt.LeftButton:
self.drawing = False
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Canvas()
window.show()
sys.exit(app.exec_())
答案 0 :(得分:0)
您可以将 self.setStyleSheet('background:transparent)
替换为 self.setStyleSheet('background-color:transparent)
。