How to find the active PyQt window and bring it to

2019-08-03 07:50发布

I'm new to PyQt. I have been searching on how to find the window of my PyQt app which is currently open and bring it to the front. This far all I've found is an example in which pywin32 was used(thus windows specific). I wanted to ask if there is a platform-independent way I can achieve the objective. Any help would be much appreciated.

Here is my code. The activateWindow() function is supposed to bring it to the front.

class TestApp(QtGui.QApplication):
    def __init__(self, argv, key):
        QtGui.QApplication.__init__(self, argv)
        self._activationWindow=None
        self._memory = QtCore.QSharedMemory()
        self._memory.setKey(key)
        if self._memory.attach():
            self._running = True
        else:
            self._running = False
            if not self._memory.create(1):
                raise RuntimeError(
                self._memory.errorString().toLocal8Bit().data())
    def isRunning(self):
        return self._running

    def activationWindow(self):
        return self._activationWindow

    def setActivationWindow(self, activationWindow):
        self._activationWindow = activationWindow

    def activateWindow(self):
        if not self._activationWindow:
            return
        self._activationWindow.setWindowState( self._activationWindow.windowState() & ~QtCore.Qt.WindowMinimized | QtCore.Qt.WindowActive)
        self._activationWindow.raise_()
        self._activationWindow.show()
        self._activationWindow.activateWindow()

标签: python pyqt4
1条回答
时光不老,我们不散
2楼-- · 2019-08-03 08:36

A complete, platform-indepenent solution is probably going to be beyond reach. Each of the platforms supported by Qt behaves in a different way, and activateWindow seems to be somewhat buggy.

To start with, here's what the Qt docs say about activateWindow:

This function performs the same operation as clicking the mouse on the title bar of a top-level window. On X11, the result depends on the Window Manager. If you want to ensure that the window is stacked on top as well you should also call raise(). Note that the window must be visible, otherwise activateWindow() has no effect.

and:

On Windows, if you are calling this when the application is not currently the active one then it will not make it the active window. It will change the color of the taskbar entry to indicate that the window has changed in some way. This is because Microsoft does not allow an application to interrupt what the user is currently doing in another application.

For more confirming evidence of the difficulties, take a look at these threads on the Qt forum:

查看更多
登录 后发表回答