pyQt5 change MainWindow Flags

polgia0 picture polgia0 · Nov 29, 2016 · Viewed 12.9k times · Source

I use python 3.4 , pyQt5 and Qt designer (Winpython distribution). I like the idea of making guis by designer and importing them in python with setupUi. I'm able to show MainWindows and QDialogs. However, now I would like to set my MainWindow, always on top and with the close button only. I know this can be done by setting Windows flags. I tried to do as following:

from PyQt5 import QtCore, QtGui, QtWidgets
import sys
class MainWindow(QtWidgets.QMainWindow,Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.setWindowFlags(QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.WindowMinimizeButtonHint)
        self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    form = MainWindow()
    form.show()
    sys.exit(app.exec_())

The MainWindow shows up (without error) but Flags are not applied. I suppose this is because I asked to change Windows properties after it was already created. Now, questions are : how I can do it without modify Ui_MainWindow directly? It is possible to change flags in Qt designer ? Thanks

Answer

ekhumoro picture ekhumoro · Nov 29, 2016

Every call of setWindowFlags will completely override the current settings, so you need to set all the flags at once. Also, you must include the CustomizeWindowHint flag, otherwise all the other hints will be ignored. The following will probably work on Windows:

    self.setWindowFlags(
        QtCore.Qt.Window |
        QtCore.Qt.CustomizeWindowHint |
        QtCore.Qt.WindowTitleHint |
        QtCore.Qt.WindowCloseButtonHint |
        QtCore.Qt.WindowStaysOnTopHint
        )

However, it is highly unlikely this will work on all platforms. "Hint" really does mean just that. Window managers are completely free to ignore these flags and there's no guarantee they will all behave in the same way.

PS:

It is not possible to set the window flags in Qt Designer.