I've run into a problem writing a test (in PyQt4). I need to test if a shortcut key, but it seems that QTest.keyClick() only works if there is a running QApplication. The example below shows the problem. Is this supposed to happen? All the examples I seen on the internet just instantiate a QApplication, but don't call exec on it.

Qt Code:
  1. import sys
  2. from PyQt4 import QtGui
  3. from PyQt4.QtCore import Qt
  4. from PyQt4.QtTest import QTest
  5.  
  6. # Create a sample widget
  7. class Widget(QtGui.QWidget):
  8. def __init__(self):
  9. super().__init__()
  10.  
  11. # Clicking the mouse on the widget will set the test keyClick, to make sure that the shortcut works.
  12. def mousePressEvent(self, *a, **k):
  13. QTest.keyClick(self, Qt.Key_C, Qt.ControlModifier)
  14. super().mousePressEvent(*a, **k)
  15.  
  16. # Slot to receive the keyClick signal
  17. def slot():
  18. print('triggered')
  19.  
  20. if __name__ == '__main__':
  21. app = QtGui.QApplication(sys.argv)
  22. w = Widget()
  23. w.show()
  24. act = QtGui.QAction('test', w)
  25. act.setShortcut(QtGui.QKeySequence('Ctrl+C'))
  26. act.setShortcutContext(Qt.WidgetWithChildrenShortcut)
  27. w.addAction(act)
  28. w.setFocusPolicy(Qt.StrongFocus)
  29. act.triggered.connect(slot)
  30.  
  31. # This does nothing, but it should call slot().
  32. QTest.keyClick(w, Qt.Key_C, Qt.ControlModifier)
  33.  
  34. # After this, the widget shows and clicking on it will trigger call the test.
  35. sys.exit(app.exec_())
To copy to clipboard, switch view to plain text mode