Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pyQt5 change MainWindow Flags

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

like image 412
polgia0 Avatar asked Nov 29 '16 13:11

polgia0


2 Answers

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.

like image 86
ekhumoro Avatar answered Nov 12 '22 21:11

ekhumoro


I would propose a different solution, because it keeps the existing flags. Reason to do this, is to NOT mingle with UI-specific presets (like that a dialog has not by default a "maximize" or "minimize" button).

self.setWindowFlags(self.windowFlags() # reuse initial flags
    & ~QtCore.Qt.WindowContextHelpButtonHint # negate the flag you want to unset
)
like image 31
Marcel Petrick Avatar answered Nov 12 '22 19:11

Marcel Petrick