PDA

View Full Version : Problem with QTest and QApplication



aquavitae
23rd January 2012, 16:12
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.


import sys
from PyQt4 import QtGui
from PyQt4.QtCore import Qt
from PyQt4.QtTest import QTest

# Create a sample widget
class Widget(QtGui.QWidget):
def __init__(self):
super().__init__()

# Clicking the mouse on the widget will set the test keyClick, to make sure that the shortcut works.
def mousePressEvent(self, *a, **k):
QTest.keyClick(self, Qt.Key_C, Qt.ControlModifier)
super().mousePressEvent(*a, **k)

# Slot to receive the keyClick signal
def slot():
print('triggered')

if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
w = Widget()
w.show()
act = QtGui.QAction('test', w)
act.setShortcut(QtGui.QKeySequence('Ctrl+C'))
act.setShortcutContext(Qt.WidgetWithChildrenShortc ut)
w.addAction(act)
w.setFocusPolicy(Qt.StrongFocus)
act.triggered.connect(slot)

# This does nothing, but it should call slot().
QTest.keyClick(w, Qt.Key_C, Qt.ControlModifier)

# After this, the widget shows and clicking on it will trigger call the test.
sys.exit(app.exec_())

wysota
23rd January 2012, 17:00
Yes, this is the correct behaviour.

aquavitae
24th January 2012, 05:18
But then how do you write a unit test (in python) for this?

wysota
24th January 2012, 09:54
You need a running event loop. The language doesn't matter here. The code you posted has an incorrect construction in the first place, read the docs for QTestLib --- you need a class inheriting QObject and you need to impement each test as a private slot of that class.

aquavitae
24th January 2012, 10:17
I see that from Qt's docs, but it isn't really clear from the PyQt4 docs, which imply that python's unittest framework should be used rather that Qt's QTestLib. Also, PyQt4 doesn't provide QTest::qExec(). Maybe I just need another cup of coffee, but it looks like the language does matter in this case...

wysota
24th January 2012, 10:29
If PyQt doesn't provide qExec then you simply can't use the framework or you need to provide your own wrapper to qExec.