digital_revenant
digital_revenant

Reputation: 3324

How to toggle window stays on top hint

I am trying to create a widget that the user should be able to select if it stays on top. Below is a sample code of what I am trying to achieve. Trying to set the Qt.WindowStaysOnTopHint after the widget has been created does not work:

from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt

app = QApplication([])
win = QWidget()

def toggleTop():
    win.setWindowFlags(Qt.WindowStaysOnTopHint)
    win.show()

button = QPushButton('Top', win)
button.clicked.connect(toggleTop)
win.show()
app.exec_()

However, if I set the flag during widget creation, it works perfectly:

from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt

app = QApplication([])
win = QWidget()
win.setWindowFlags(Qt.WindowStaysOnTopHint)
win.show()
app.exec_()

OS is Ubuntu 18.04.

Upvotes: 1

Views: 975

Answers (1)

ekhumoro
ekhumoro

Reputation: 120568

Your toggleTop function is currently overwriting all the window flags with the same flag every time. To toggle a single window flag, you need to explicitly reset it based on the current state of the flag:

def toggleTop():
    # get the current state of the flag
    on = bool(win.windowFlags() & Qt.WindowStaysOnTopHint)
    # toggle the state of the flag
    win.setWindowFlag(Qt.WindowStaysOnTopHint, not on)
    win.show()

Upvotes: 1

Related Questions