Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Keyboard Events
Forum Update on Monday, May 27th 2025

Keyboard Events

Scheduled Pinned Locked Moved Unsolved General and Desktop
5 Posts 2 Posters 362 Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • PythonShinobiP Offline
    PythonShinobiP Offline
    PythonShinobi
    wrote on last edited by
    #1

    I want to be able to get a visual representation on a GUI keyboard I am creating when I press my physical keyboard. But the only feedback I get is when I press the space key on the keyboard and it triggers other keys on the GUI, How do I fix it? Please and thank you.

    C 1 Reply Last reply
    0
    • PythonShinobiP PythonShinobi

      I want to be able to get a visual representation on a GUI keyboard I am creating when I press my physical keyboard. But the only feedback I get is when I press the space key on the keyboard and it triggers other keys on the GUI, How do I fix it? Please and thank you.

      C Offline
      C Offline
      ChrisW67
      wrote on last edited by
      #2

      @PythonShinobi said in Keyboard Events:

      How do I fix it?

      You are going to have to share at least some of what"it" currently is.

      1 Reply Last reply
      3
      • PythonShinobiP Offline
        PythonShinobiP Offline
        PythonShinobi
        wrote on last edited by
        #3
        This post is deleted!
        1 Reply Last reply
        0
        • PythonShinobiP Offline
          PythonShinobiP Offline
          PythonShinobi
          wrote on last edited by
          #4

          class KeyBoard(QWidget):
          def init(self):
          super().init()
          self.setWindowTitle('Virtual Keyboard')
          self.setGeometry(100, 100, 600, 200)
          self.generalLayout = QVBoxLayout()

              self.capsLockActive = False  # Initial state of the Caps Lock
          
              self._createDisplay()
              self._createButtons()
          
              self.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
              self.setLayout(self.generalLayout)        
          
              self.setFocus()
          
          def _createDisplay(self):
              self.textInput = QLineEdit()
              # Add label to display cursor position
              self.cursorPositionLabel = QLabel()
              self.cursorPositionLabel.setAlignment(Qt.AlignmentFlag.AlignCenter)
              self.generalLayout.addWidget(self.cursorPositionLabel)
          
              self.generalLayout.addWidget(self.textInput)        
          
          def _createButtons(self):
              # Create rows of keys.
              self.buttons = {}  # Used to keep track of all the buttons in the keyboard.
              keys = [
                  ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', 'Clear'],
                  ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '<-', '->'],
                  ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', "Enter"],     
                  ['z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/'],          
                  ['Shift', 'Ctrl', 'Space', 'Alt', 'Backspace', 'Caps Lock'], 
              ]
          
              for row in keys:
                  rowLayout = QHBoxLayout()  # Create a QHBoxLayout for each row of buttons
                  for col in row:  # For every item in a list.
                      button = QPushButton(col)  # Create a button.
                      button.setStyleSheet("QPushButton:hover { background-color: #45a049; } QPushButton:pressed { background-color: #0d8050; }")
                      if col == 'Space':
                          button.setFixedWidth(100)
                      rowLayout.addWidget(button)   # Add each button to the row layout
                      self.buttons[col] = button
                      # Connect the clicked signal of the button to the corresponding slot.
                      button.clicked.connect(lambda clicked, ch=col: self.onKeyClicked(ch))
                  self.generalLayout.addLayout(rowLayout)  # Add the row layout to the general
          
          def updateCursorPositionLabel(self):
              """Display the position of the cursor in the text input."""
              cursorPosition = self.textInput.cursorPosition()  # Retrieve the cursor positon.
              self.cursorPositionLabel.setText(f'Cursor Position: {cursorPosition}')
          
          def onKeyClicked(self, char):
              """Handle the click event of a virtual keyboard button.
              Parameters: char (str): The character associated with the clicked button."""
              if char == 'Backspace':
                  self.textInput.backspace()
              elif char == 'Space':
                  self.textInput.insert(' ')
              elif char in ['Shift', 'Ctrl', 'Alt']:
                  pass
              elif char == 'Clear':
                  self.textInput.clear()
              elif char == 'Caps Lock':
                  self.capsLockActive = not self.capsLockActive  # Toggle Caps Lock state.
                  # Toggle the case of character labels on all buttons
                  for button in self.buttons.values():
                      if self.capsLockActive:
                          button.setText(button.text().upper())
                      else:
                          button.setText(button.text().lower())
              elif char == '<-':
                  # Retrieve the current cursor position.
                  cursorPosition = self.textInput.cursorPosition()
                  self.textInput.setCursorPosition(cursorPosition - 1)
              elif char == '->':
                  # Retrieve the current cursor position.
                  cursorPosition = self.textInput.cursorPosition()
                  self.textInput.setCursorPosition(cursorPosition + 1)
              else:
                  if self.capsLockActive:
                      char = char.upper()
                  self.textInput.insert(char)
              
              self.updateCursorPositionLabel()
          
          def keyPressEvent(self, e):
              if e.key() == Qt.Key_Space:
                  self.onKeyClicked('Space')
              elif e.key() == Qt.Key_Backspace:
                  print(0)
          
          C 1 Reply Last reply
          0
          • PythonShinobiP PythonShinobi

            class KeyBoard(QWidget):
            def init(self):
            super().init()
            self.setWindowTitle('Virtual Keyboard')
            self.setGeometry(100, 100, 600, 200)
            self.generalLayout = QVBoxLayout()

                self.capsLockActive = False  # Initial state of the Caps Lock
            
                self._createDisplay()
                self._createButtons()
            
                self.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
                self.setLayout(self.generalLayout)        
            
                self.setFocus()
            
            def _createDisplay(self):
                self.textInput = QLineEdit()
                # Add label to display cursor position
                self.cursorPositionLabel = QLabel()
                self.cursorPositionLabel.setAlignment(Qt.AlignmentFlag.AlignCenter)
                self.generalLayout.addWidget(self.cursorPositionLabel)
            
                self.generalLayout.addWidget(self.textInput)        
            
            def _createButtons(self):
                # Create rows of keys.
                self.buttons = {}  # Used to keep track of all the buttons in the keyboard.
                keys = [
                    ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', 'Clear'],
                    ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '<-', '->'],
                    ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', "Enter"],     
                    ['z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/'],          
                    ['Shift', 'Ctrl', 'Space', 'Alt', 'Backspace', 'Caps Lock'], 
                ]
            
                for row in keys:
                    rowLayout = QHBoxLayout()  # Create a QHBoxLayout for each row of buttons
                    for col in row:  # For every item in a list.
                        button = QPushButton(col)  # Create a button.
                        button.setStyleSheet("QPushButton:hover { background-color: #45a049; } QPushButton:pressed { background-color: #0d8050; }")
                        if col == 'Space':
                            button.setFixedWidth(100)
                        rowLayout.addWidget(button)   # Add each button to the row layout
                        self.buttons[col] = button
                        # Connect the clicked signal of the button to the corresponding slot.
                        button.clicked.connect(lambda clicked, ch=col: self.onKeyClicked(ch))
                    self.generalLayout.addLayout(rowLayout)  # Add the row layout to the general
            
            def updateCursorPositionLabel(self):
                """Display the position of the cursor in the text input."""
                cursorPosition = self.textInput.cursorPosition()  # Retrieve the cursor positon.
                self.cursorPositionLabel.setText(f'Cursor Position: {cursorPosition}')
            
            def onKeyClicked(self, char):
                """Handle the click event of a virtual keyboard button.
                Parameters: char (str): The character associated with the clicked button."""
                if char == 'Backspace':
                    self.textInput.backspace()
                elif char == 'Space':
                    self.textInput.insert(' ')
                elif char in ['Shift', 'Ctrl', 'Alt']:
                    pass
                elif char == 'Clear':
                    self.textInput.clear()
                elif char == 'Caps Lock':
                    self.capsLockActive = not self.capsLockActive  # Toggle Caps Lock state.
                    # Toggle the case of character labels on all buttons
                    for button in self.buttons.values():
                        if self.capsLockActive:
                            button.setText(button.text().upper())
                        else:
                            button.setText(button.text().lower())
                elif char == '<-':
                    # Retrieve the current cursor position.
                    cursorPosition = self.textInput.cursorPosition()
                    self.textInput.setCursorPosition(cursorPosition - 1)
                elif char == '->':
                    # Retrieve the current cursor position.
                    cursorPosition = self.textInput.cursorPosition()
                    self.textInput.setCursorPosition(cursorPosition + 1)
                else:
                    if self.capsLockActive:
                        char = char.upper()
                    self.textInput.insert(char)
                
                self.updateCursorPositionLabel()
            
            def keyPressEvent(self, e):
                if e.key() == Qt.Key_Space:
                    self.onKeyClicked('Space')
                elif e.key() == Qt.Key_Backspace:
                    print(0)
            
            C Offline
            C Offline
            ChrisW67
            wrote on last edited by
            #5

            @PythonShinobi said in Keyboard Events:

            def keyPressEvent(self, e):
            if e.key() == Qt.Key_Space:
            self.onKeyClicked('Space')
            elif e.key() == Qt.Key_Backspace:
            print(0)

            This does something when a space or backspace is pressed and nothing for any other key event received. By default this event handler accepts every QKeyEvent it receives, so no other processing will occur for key strokes.

            1 Reply Last reply
            1

            • Login

            • Login or register to search.
            • First post
              Last post
            0
            • Categories
            • Recent
            • Tags
            • Popular
            • Users
            • Groups
            • Search
            • Get Qt Extensions
            • Unsolved