ivaquero
ivaquero

Reputation: 91

PyQT6/PySide6: How to make a QWidget always on top of screen?

I am making a floating clock based on PySide6, its main part is as follows

How can I make this program always on top of the screen, even in full screen mode?

The self.setWindowFlags(Qt.WindowStaysOnTopHint) method doesn't seem to work.

import sys

from PySide6.QtCore import QPoint, Qt, QTime, QTimer
from PySide6.QtGui import QAction, QFont, QMouseEvent
from PySide6.QtWidgets import QApplication, QLabel, QMenu, QVBoxLayout, QWidget


class Clock(QWidget):

    def __init__(self, parent=None) -> None:
        super().__init__(parent)

        self.left = 1100
        self.top = 800
        self.width = 320
        self.height = 60
        # UI
        self.initUI()

    def initUI(self) -> None:

        # geometry of main window
        self.setGeometry(self.left, self.top, self.width, self.height)

        # hide frame
        self.setWindowFlags(Qt.WindowStaysOnTopHint)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)

        # font
        font = QFont()
        font.setFamily("Arial")
        font.setPointSize(50)

        # label object
        self.label = QLabel()
        self.label.setAlignment(Qt.AlignCenter)
        self.label.setFont(font)

        # layout
        layout = QVBoxLayout(self, spacing=0)

        layout.addWidget(self.label)  # add label
        self.setLayout(layout)

        # timer object
        timer = QTimer(self)
        timer.timeout.connect(self.showTime)
        timer.start(1000)  # update the timer per second
        self.show()

    def showTime(self) -> None:

        current_time = QTime.currentTime()  # get the current time
        label_time = current_time.toString('hh:mm')  # convert timer to string
        self.label.setText(label_time)  # show it to the label


if __name__ == '__main__':

    App = QApplication(sys.argv)
    clock = Clock()
    clock.show()  # show all the widgets
    App.exit(App.exec())  # start the app

Upvotes: 2

Views: 4372

Answers (2)

Terry
Terry

Reputation: 73

Refer to the "WindowType" for WindowStaysOnTopHint flag

self.setWindowFlag(Qt.WindowType.WindowStaysOnTopHint, True)

Upvotes: 1

GreedyTeufel
GreedyTeufel

Reputation: 113

You are using the wrong method for setting the flags individually. You should use this method instead: setWindowFlag NOT setWindowFlags (without the "s" at the end). This will solve Your issue:

self.setWindowFlag(Qt.WindowStaysOnTopHint, True)
self.setWindowFlag(Qt.FramelessWindowHint, True)

To use setWindowFlags (with the "s" at the end) You should combine the flags with the bitwise OR. Here is the (C++) Qt-example for that https://doc.qt.io/qt-6/qtwidgets-widgets-windowflags-example.html

Upvotes: 4

Related Questions