For my application I want to have a main window that has a button and a shortcut handler that is able to catch Hotkeys even when the python app is not in focus. The easiest solution was to use a Pynput Global HotKey Listener. The Code below brings this functionality but the window that is opened from the hotkey is broken. It has no content, can't be moved, minimized or closed. It also sometimes crahses the application entirely. The Window opened from the button on the other hand works perfectly fine even though both are calling the same method.
This doesn't make sense to me so all help is greatly appreciated.
import sys
from PyQt6.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
from pynput import keyboard
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle("Main Window")
self.setGeometry(100, 100, 300, 200)
layout = QVBoxLayout()
self.button = QPushButton("Open Second Window")
self.button.clicked.connect(self.open_second_window)
layout.addWidget(self.button)
self.setLayout(layout)
self.show()
def open_second_window(self):
self.second_window = SecondWindow()
self.second_window.show()
class SecondWindow(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Second Window")
self.setGeometry(200, 200, 300, 200)
layout = QVBoxLayout()
self.button = QPushButton("Close")
self.button.clicked.connect(self.close)
layout.addWidget(self.button)
self.setLayout(layout)
class HotKeyListener:
def __init__(self):
self.listener = keyboard.GlobalHotKeys({"<ctrl>+<alt>+i": self.open_second_window})
self.listener.start()
def open_second_window(self):
second_window = SecondWindow()
second_window.show()
def main():
app = QApplication(sys.argv)
window = MainWindow()
hotkey_listener = HotKeyListener()
sys.exit(app.exec())
if __name__ == "__main__":
main()