Skip to content

[PyQt5] Keep the window at the top or bottom of the screen

I used to think that it would be quite difficult to keep the window of the program at the top or bottom in PyQt5.

But I’m wrong. It just need to one-line to set it.

Let’s talk about how to use setWindowFlags() to set the window position now!

If you want to know more about PyQt5, you can refer to their PyPI: https://pypi.org/project/PyQt5/

If you want to read some PyQt5 teaching, maybe you can refer to what I wrote before: [PyQt5] Tutorial(1) Install PyQt5 and print “Hello World!”


setWindowFlags

First, suppose we have a program like this:

# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import *


class MainWindow(QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.resize(200, 100)

        self.label_display = QLabel(self)
        self.label_display.setGeometry(0, 0, 100, 10)
        self.label_display.setText('Hello TEST!!!')


if __name__ == '__main__':
    app = QApplication([])
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())



Output:


If you want to keep this window always in the top (front):

from PyQt5.QtCore import *



First you need to import QtCore that is the Qt module we need.

Then we write in the place where the program is initialized:

self.setWindowFlags(Qt.WindowStaysOnTopHint)



You can test to see if the window of the program has been kept at the forefront?

Conversely, if you want the program to remain as a desktop widget (or other function) at the end:

self.setWindowFlags(Qt.WindowStaysOnBottomHint)



that’s it!

Simply put, it is to set setWindowFlags(), and then decide whether to put in Qt.WindowStaysOnBottomHint or Qt.WindowStaysOnTopHint respectively.

Leave a Reply