Как как выполнить событие с keyPressEvent один раз

Рейтинг: 1Ответов: 1Опубликовано: 05.04.2023

Запускается скрипт. При нажатие на Q будет выводиться текст.
Моя задача сделать так, чтобы при повторном нажатие на Q, текст не выводился, другими словами, эта функция больше не работала.

...
    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Escape:
            self.close()

        if event.key() == Qt.Key_Q:
            print('apple')

...

Ответы

▲ 0Принят

Пожалуйста, ВСЕГДА предоставляйте минимально-воспроизводимый пример.

Попробуйте так:

import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QApplication


class Example(QWidget):
    def __init__(self):
        super().__init__()

        self.flag = True

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Escape:
            self.close()

        if event.key() == Qt.Key_Q and self.flag:
            print('apple')
            self.flag = False


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Example()
    w.show()
    sys.exit(app.exec_())