【发布时间】:2012-08-25 03:30:14
【问题描述】:
当应用程序从另一台机器接收到指定消息时,我想让 PyQT4 窗口(@987654321@)跳转到前面。 通常窗口是最小化的。
我尝试了raise_() 和show() 方法,但它不起作用。
【问题讨论】:
-
在 PyQt5 中
show()和顺序raise_()对于从 QtWidgets.QMainWindow 派生的类对我来说工作正常
当应用程序从另一台机器接收到指定消息时,我想让 PyQT4 窗口(@987654321@)跳转到前面。 通常窗口是最小化的。
我尝试了raise_() 和show() 方法,但它不起作用。
【问题讨论】:
show() 和顺序 raise_() 对于从 QtWidgets.QMainWindow 派生的类对我来说工作正常
这行得通:
# 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()
我在 Win7 上都需要这两个。
setWindowState 恢复最小化窗口并提供焦点。但是如果窗口只是失去焦点而不是最小化,它就不会获得焦点。
activateWindow 提供焦点但不恢复最小化状态。
同时使用两者都有预期的效果。
【讨论】:
这对我来说可以提高窗户,但不能一直放在上面:
# bring window to top and act like a "normal" window!
window.setWindowFlags(window.windowFlags() | QtCore.Qt.WindowStaysOnTopHint) # set always on top flag, makes window disappear
window.show() # makes window reappear, but it's ALWAYS on top
window.setWindowFlags(window.windowFlags() & ~QtCore.Qt.WindowStaysOnTopHint) # clear always on top flag, makes window disappear
window.show() # makes window reappear, acts like normal window now (on top now but can be underneath if you raise another window)
【讨论】:
window.setWindowFlags(window.windowFlags() | QtCore.Qt.WindowStaysOnTopHint); window.show()
上述方法我没有任何运气,最终不得不直接使用win32 api,使用C版本here的hack。这对我有用:
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()
【讨论】:
对于使用 NVidia GPU 的 Windows 10 上的我来说,这很有效:
from PyQt4 import QtCore
# create window here...
window.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
我在这个答案上找到了它:https://stackoverflow.com/a/12280956/4549682
【讨论】:
对于被这个问题激怒并且没有设法使用作为答案给出的任何一种方法来修复它的人(例如,如果我在启动 python 脚本之后但在 Qt 窗口之前单击另一个窗口,则对我而言,PyQt5 没有任何效果出现了),这就是最终对我有用的技巧:
wnd.showMinimized() # this is the trick: minimize first
wnd.show() # or wnd.showMaximized() if you want it shown maximized
【讨论】: