0

I'm trying to test if a shortcut is working using PyQt5 and QTest. Here is my code:

Main.py

from PyQt5.QtGui import QKeySequence
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QApplication, QPushButton


class Window(QWidget):

    def __init__(self):
        super().__init__()

        self.more_btn = QPushButton("More")
        self.more_btn.clicked.connect(self.on_clicked)
        self.more_btn.setShortcut(QKeySequence.Undo)

        vbox = QVBoxLayout()
        vbox.addWidget(self.more_btn)
        self.setLayout(vbox)

    def on_clicked(self):
        print("Item clicked")

test_main.py

import sys
import unittest

from PyQt5.QtGui import QKeySequence
from PyQt5.QtTest import QTest
from PyQt5.QtWidgets import QApplication

from Main import Window


class MainTestCase(unittest.TestCase):

    def test_main(self):
        app = QApplication(sys.argv)
        form = Window()
        QTest.keySequence(form, QKeySequence.Undo)

When I run test_main, item_clicked should be printed, but it doesn't. I tried to debug the program and set the breatpoint at the print("Item clicked") line, it didn't stop. It seems that QTest.keySequence didn't work. Why? How should I make it work?

Searene
  • 25,920
  • 39
  • 129
  • 186
  • 1
    I've never used QTest, so I'm not completely sure, but the QApplication should be *running* its event loop in order to process events, even in test mode. – musicamante May 06 '22 at 17:11
  • when your `test_main.py` is called? logically you cant call main in other files, main is the first file that will run and call, you should call others inside main. – Parisa.H.R May 10 '22 at 08:14

0 Answers0