pythongifqwidgetpyside6qapplication

Pushing QWidget Window to topmost in Python


I'm new to Python and have mostly learnt C# in the past. I am creating a QWidget class:

class Window(QWidget):
    def __init__(self, gif, width, height):
        super().__init__()

        self.setGeometry(400, 200, width, height)
        self.setWindowTitle("Python Run GIF Images")
        self.setWindowIcon(QIcon('icons/qt.png'))

        label = QLabel(self)
        movie = QMovie(gif)
        label.setMovie(movie)
        movie.start()

And then define a function that creates a QApplication and then the Window:

def run_gif(gif, width, height):

    app = QApplication([])
    window = Window(gif, width, height)
    window.show()
    app.exec()
    app.shutdown()

My issue is getting the gif to show topmost when it is launched. There is a Topmost property you can set on a Winform in C# which means no other window or other app you click on will cover the Window. This isn't essential but I want it to at least be shown above the code editor it is launched from so that the user doesn't have to select the Window to see the gif contained in the Window. I've spent hours looking at properties I can set either in the class or the method and not getting the result I need.

However, when I call the run_gif method for the second time, it does show it topmost, but along with the below exception (at least I think it's an exception from what I'm reading, it doesn't affect the running of the program other than printing to the console).

QApplication::regClass: Registering window class 'Qt640ScreenChangeObserverWindow' failed. (Class already exists.)

The only advice I can find on this error is not Python-specific and I don't really understand it. Maybe I'm being a bit ambitious for my early stage learning Python but not really seeing anything much on this error.

This is using PySide6.


Solution

  • Using setWindowFlag(Qt.WindowType.WindowStaysOnTopHint, True) seems to be working for me so far.

    Example:

    from PySide6.QtWidgets import *
    from PySide6.QtCore import *
    from PySide6.QtGui import *
    
    
    class Window(QWidget):
    
        def __init__(self, parent=None):
            super().__init__(parent=parent)
            self.layout = QVBoxLayout(self)
            self.resize(200,100)
            self.label = QLabel("Always on top...")
            self.layout.addWidget(self.label)
            self.setWindowFlag(Qt.WindowType.WindowStaysOnTopHint, True)  # <--
    
    if __name__ == '__main__':
        app = QApplication([])
        window = Window()
        window.show()
        app.exec()