i can’t detect the state of the shift and ctrl keys

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):

        self.setGeometry(10, 30, 10, 10)

        timer = QTimer(self, interval=1000, timeout=self.detect)

    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.")
            print("Neither Shift nor Ctrl is down.")

if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    ex = App()


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.

Leave a Comment

Your email address will not be published.

Scroll to Top