我正在制作一个基于PySide6的浮动时钟,其主要部分如下
如何使该程序始终位于屏幕顶部,即使在全屏模式下也是如此?
self.setWindowFlags(Qt.WindowStaysOnTopHint)
这个方法好像不行。
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
您使用了错误的方法来单独设置标志。您应该改用此方法:
setWindowFlag
NOT setWindowFlags
(末尾不带“s”)。这将解决您的问题:
self.setWindowFlag(Qt.WindowStaysOnTopHint, True)
self.setWindowFlag(Qt.FramelessWindowHint, True)
要使用
setWindowFlags
(末尾带有“s”),您应该将标志与按位或组合起来。
这是(C++)Qt 示例 https://doc.qt.io/qt-6/qtwidgets-widgets-windowflags-example.html
self.setWindowFlag(Qt.WindowType.WindowStaysOnTopHint, True)