I'm on Windows 10 and I have a PyQt5 Application I launch using a .bat file to use the venv interpreter.
When I call the script using python my_script.py
it opens the main window in focus, but also shows the Python console in background. To get rid of the console, I tried launching it with pythonw my_script.py
, but then it silently opens in background.
I tried things like window.setWindowState(Qt.WindowState.WindowActive)
or window.setFocus()
, but this only makes the icon blink in the task bar. Other Google results said that Windows does not allow programs to easily grab focus anymore, but then again, python
can do it on start-up, so I would like to replicate that behavior with pythonw
.
Below you can find testing code and the batch file, context was launching it from a custom URI protocol.
# https://stackoverflow.com/a/38205984 to register any protocol for testing
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
from PyQt5.QtCore import Qt
class MainWindow(QMainWindow):
def __init__(self, title):
super().__init__()
self.setWindowTitle("Test App")
label = QLabel(title)
self.setCentralWidget(label)
if __name__ == '__main__':
if len(sys.argv) == 1:
the_title = "I got no arguments"
else:
the_title = f"I was run with argument {sys.argv[1]}"
app = QApplication(sys.argv)
window = MainWindow(the_title)
window.show()
window.setFocus()
app.exec()
and
cd %~dp0
call ..\venv\Scripts\activate
start "" "pythonw" "test_url_scheme_one.py" "%1"
deactivate
Replacing the batch file with the following fixed it:
start "" "C:\path\to\venv\Scripts\pythonw.exe" "C:\path\to\my_script.py" "%1"
Now the window gets started in foreground and in focus.