How to use QTest.keySequence?

101 Views Asked by At

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?

0

There are 0 best solutions below