lang/pysideex/ TranslucentWindows


This is a barebones example of what is necessary for a 'hud' type overlay that shows temporarily.

import sys
from PySide6.QtCore import *
from PySide6.QtGui import *
from PySide6.QtWidgets import *

HUDTIME=2000
KILLTIME=4000
class Hud(QWidget):
  def __init__(self):
    super().__init__()

    # size and position -- possibly necessary to recompute, resize and move depending on hud contents
    w = 200
    h = 200
    self.resize(w,h)
    screen = QGuiApplication.primaryScreen()
    rect = screen.geometry()
    x = rect.width()-w
    y = rect.height()-h
    print(w,h,x,y)
    self.move(x,y)

    # attributes for display
    self.number = "My"
    self.font = QFont("Optima",80)
    self.color = QColor(100,255,100)
    self.ocolor = Qt.black
    self.pen = QPen(self.ocolor,16)
    self.showtime = 5

    # two timers: one to auto-hide the hud, the second to kill the entire application
    self.timer = QTimer(self)
    self.dtimer = QTimer(self)

    # so a call to show() knows whether we are already showing or not (and vice versa for hide())
    self.showing = False

    # window attributes
    self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
    self.setAttribute(Qt.WA_TranslucentBackground)

  def paintEvent(self,event):
    with QPainter(self) as p:
      rect = QRect(0,25,200,150)
      path = QPainterPath()
      path.addText(0,0,self.font,str(self.number))
      p.translate(0,150)

      # draw twice so that the black outline is _behind_ the fill
      p.setPen(self.pen)
      p.drawPath(path)
      p.setBrush(self.color)
      p.setPen(Qt.NoPen)
      p.drawPath(path)

  def show(self,x):
    self.number = x
    if not self.showing:
      super().show()
      self.showing = True
      self.timer.stop()
    self.update()
    self.timer.singleShot(HUDTIME,self.hide)

  def hide(self):
    if self.showing:
      self.showing = False
      super().hide()

  def test(self):
    timer = QTimer(self)
    self.show("My")
    timer.singleShot(1000, lambda *t: self.show("Xy"))
    self.dtimer.singleShot(KILLTIME,self.finish)

  def finish(self):
    app.quit()

app = QApplication(sys.argv)
hud = Hud()
hud.test()
exit(app.exec())