@sssss12

Как при нажатие на клавишу клавиатуры применять функцию обработчик в pyqt5?

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QHBoxLayout, QLineEdit


def exits():
    exit()


def translator(a):
    if str(a)[-1] == "0":
        a = int(a)
    return a


def text_input(meaning):
    if "Н" in input_line.text():
        update()
        input_line.setText(meaning)
    elif len(input_line.text()) < 9:
        input_line.setText(str(input_line.text()) + meaning)


def operations_input(meaning):
    global operation
    global frist_number
    if input_line.text() != "":
        frist_number = input_line.text()
        operation = meaning
        input_line.setText("")
    elif input_line.text() == "" and meaning != "-":
        operation = meaning
        input_line.setText("")
    elif input_line.text() == "" and meaning == "-":
        input_line.setText(meaning)


def summa():
    try:
        global second_number
        second_number = input_line.text()
        if operation == "-":
            summa_numbers = float(frist_number) - float(second_number)
            print(frist_number)
            print(operation)
            print(second_number)
            print(summa_numbers)
            summa_numbers = translator(summa_numbers)
        elif operation == "+":
            summa_numbers = float(frist_number) + float(second_number)
            summa_numbers = translator(summa_numbers)
        elif operation == "*":
            summa_numbers = float(frist_number) * float(second_number)
            summa_numbers = translator(summa_numbers)
        else:
            summa_numbers = float(frist_number) / float(second_number)
            summa_numbers = translator(summa_numbers)
        input_line.setText(str(summa_numbers))
    except:
        input_line.setText("Неверный ввод!")


def delete_nambers():
    input_line.setText(input_line.text()[:-1])


def update():
    input_line.setText("")
    global frist_number
    global second_number
    global operation
    frist_number, second_number, operation = 0, "N", 0


but_num = []
keys = [Qt.Key_0, Qt.Key_1, Qt.Key_2,  Qt.Key_3, Qt.Key_4, Qt.Key_5, Qt.Key_6, Qt.Key_7, Qt.Key_8, Qt.Key_9]


app = QApplication([])
main_win = QWidget()
main_win.show()
main_win.setWindowTitle("Канкулятор")
main_win.resize(200, 250)

frist_number = 0
second_number = 0
operation = 0


v_line = QVBoxLayout()
h_zero_line = QHBoxLayout()
h_one_line = QHBoxLayout()
h_two_line = QHBoxLayout()
h_three_line = QHBoxLayout()
h_four_line = QHBoxLayout()

for i in range(10):
    number_i = QPushButton(str(i))
    but_num.append(number_i)

leaving = QPushButton("Выход")
answer_button = QPushButton("=")
plus_button = QPushButton("+")
minus_button = QPushButton("-")
multiply = QPushButton("*")
divide = QPushButton("/")
c = QPushButton("C")
delete = QPushButton("<-")

input_line = QLineEdit()

h_zero_line.addWidget(input_line, alignment=Qt.AlignVCenter)
h_zero_line.addWidget(delete, alignment=Qt.AlignVCenter)
h_zero_line.addWidget(c, alignment=Qt.AlignVCenter)
h_one_line.addWidget(but_num[1], alignment=Qt.AlignVCenter)
h_one_line.addWidget(but_num[2], alignment=Qt.AlignVCenter)
h_one_line.addWidget(but_num[3], alignment=Qt.AlignVCenter)
h_one_line.addWidget(answer_button, alignment=Qt.AlignVCenter)
h_two_line.addWidget(but_num[4], alignment=Qt.AlignVCenter)
h_two_line.addWidget(but_num[5], alignment=Qt.AlignVCenter)
h_two_line.addWidget(but_num[6], alignment=Qt.AlignVCenter)
h_two_line.addWidget(leaving, alignment=Qt.AlignVCenter)
h_three_line.addWidget(but_num[7], alignment=Qt.AlignVCenter)
h_three_line.addWidget(but_num[8], alignment=Qt.AlignVCenter)
h_three_line.addWidget(but_num[9], alignment=Qt.AlignVCenter)
h_three_line.addWidget(multiply, alignment=Qt.AlignVCenter)
h_four_line.addWidget(plus_button, alignment=Qt.AlignVCenter)
h_four_line.addWidget(but_num[0], alignment=Qt.AlignVCenter)
h_four_line.addWidget(minus_button, alignment=Qt.AlignVCenter)
h_four_line.addWidget(divide, alignment=Qt.AlignVCenter)

leaving.clicked.connect(exits)
delete.clicked.connect(delete_nambers)
but_num[0].clicked.connect(lambda: text_input("0"))
but_num[1].clicked.connect(lambda: text_input("1"))
but_num[2].clicked.connect(lambda: text_input("2"))
but_num[3].clicked.connect(lambda: text_input("3"))
but_num[4].clicked.connect(lambda: text_input("4"))
but_num[5].clicked.connect(lambda: text_input("5"))
but_num[6].clicked.connect(lambda: text_input("6"))
but_num[7].clicked.connect(lambda: text_input("7"))
but_num[8].clicked.connect(lambda: text_input("8"))
but_num[9].clicked.connect(lambda: text_input("9"))
c.clicked.connect(update)
plus_button.clicked.connect(lambda: operations_input("+"))
minus_button.clicked.connect(lambda: operations_input("-"))
multiply.clicked.connect(lambda: operations_input("*"))
divide.clicked.connect(lambda: operations_input("/"))
answer_button.clicked.connect(summa)

v_line.addLayout(h_zero_line)
v_line.addLayout(h_one_line)
v_line.addLayout(h_two_line)
v_line.addLayout(h_three_line)
v_line.addLayout(h_four_line)

main_win.setLayout(v_line)
app.exec_()


Хочу сделать так чтобы qlineedit можно было вводить с клавиатуры и при этом функции обработчики работали
p.s я начинающий программист)
  • Вопрос задан
  • 20 просмотров
Пригласить эксперта
Ответы на вопрос 1
@dim5x
ЗИ, ИБ. Помогли? Поблагодарите. Отметьте ответом.
В цикле создания кнопок сразу их инициализировать, используя метод setShortcutкласса QPushButton, чтобы связать функцию с конкретной клавишей?
for i in range(10):
    number_i = QPushButton(str(i))
    number_i.setShortcut(keys[i])
    number_i.clicked.connect(lambda i=i: text_input(i))
    but_num.append(number_i)


То же и для операций:
but_op = []
operations = ["+", "-", "*", "/"]
for op in operations:
    button = QPushButton(op)
    button.setShortcut(QKeySequence(Qt.Key_Plus if op == "+" else Qt.Key_Minus if op == "-" else Qt.Key_Asterisk if op == "*" else Qt.Key_Slash))
    button.clicked.connect(lambda op=op: operations_input(op))
    but_op.append(button)
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы