NEVER use time.sleep in the main thread as it blocks the eventloop, if you want to do periodic tasks then use a QTimer:
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtWidgets import QApplication, QWidget
class App(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(10, 30, 10, 10)
self.show()
timer = QTimer(self, interval=1000, timeout=self.detect)
timer.start()
def detect(self):
modifiers = QApplication.keyboardModifiers()
if modifiers == Qt.ShiftModifier:
print("Shift key is down; Ctrl key is up.")
elif modifiers == Qt.ControlModifier:
print("Shift key is up; Ctrl key is down")
elif modifiers == (Qt.ControlModifier | Qt.ShiftModifier):
print("Shift and Ctrl keys are both down.")
else:
print("Neither Shift nor Ctrl is down.")
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
Note: You must bear in mind that Qt only detects the pressed keys if the Qt window has the focus. If you want to detect if these keys are pressed even when the Qt window does not have the focus then you will have to use libraries from the OS or libraries that like pynput, keyboard
CLICK HERE to find out more related problems solutions.