M
M
Miri_Skava2019-05-22 20:33:54
Python
Miri_Skava, 2019-05-22 20:33:54

How to handle keyboard keystrokes?

Hello!
Please tell me how to set the action on pressing a key, just if any key was pressed.

import sys  
from PyQt5 import QtCore, QtGui, QtWidgets
import start_menu, dialog, login, registration
import mysql.connector
import random
import datetime

class Reg(QtWidgets.QDialog, registration.Ui_registration):
        def __init__(self):
            super().__init__()
            self.setupUi(self) 
            self.enterstr.returnPressed.connect(self.dinamic)#enterstr это QLineEdit
        def dinamic(self):
            self.keyholdtime.setText("hhh")
..........

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2019-05-22
@Miri_Skava

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget
from PyQt5.QtCore import QSize    


class ExampleWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setMinimumSize(QSize(320, 240))
        self.setWindowTitle('Example')

        central_widget = QWidget(self)
        grid_layout = QGridLayout(central_widget)
        self.setCentralWidget(central_widget)

        self._label = QLabel('', self)
        self._label.setAlignment(QtCore.Qt.AlignCenter)
        grid_layout.addWidget(self._label, 0, 0)

        self._counter = 0

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Q:
            self._counter += 1
            self._label.setText('Клавиша Q нажата {} раз'.format(self._counter))
        event.accept()


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    main_window = ExampleWindow()
    main_window.show()
    sys.exit(app.exec_())

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question