How to make a PyQT4 window jump to the front?

2019-01-26 05:06发布

问题:

I want to make a PyQT4 window(QtGui.QMainWindow) jump to the front when the application received a specified message from another machine. Usually the window is minimized.

I tried the raise_() and show() method but it doesn't work.

回答1:

This works:

# this will remove minimized status 
# and restore window with keeping maximized/normal state
window.setWindowState(window.windowState() & ~QtCore.Qt.WindowMinimized | QtCore.Qt.WindowActive)

# this will activate the window
window.activateWindow()

Both are required for me on Win7.

setWindowState restores the minimized window and gives focus. But if the window just lost focus and not minimized, it won't give focus.

activateWindow gives focus but doesn't restore the minimized state.

Using both has the desired effect.



回答2:

I didn't have any luck with the above methods, ended up having to use the win32 api directly, using a hack for the C version here. This worked for me:

from win32gui import SetWindowPos
import win32con

SetWindowPos(window.winId(),
             win32con.HWND_TOPMOST, # = always on top. only reliable way to bring it to the front on windows
             0, 0, 0, 0,
             win32con.SWP_NOMOVE | win32con.SWP_NOSIZE | win32con.SWP_SHOWWINDOW)
SetWindowPos(window.winId(),
             win32con.HWND_NOTOPMOST, # disable the always on top, but leave window at its top position
             0, 0, 0, 0,
             win32con.SWP_NOMOVE | win32con.SWP_NOSIZE | win32con.SWP_SHOWWINDOW)
window.raise_()
window.show()
window.activateWindow()


标签: python pyqt4