How to simulate mouse click within QTestLib on items and elements of QTreeWidget/QListWidget
Context
While writing some unit tests for my program, I encountered a problem of how to simulate the mouse event within the Qt widgets such as QListWidget
and QTreeWidget
. In particular, I wanted to trigger two types of events:
- mouse click on an item of my widget
- mouse click on a button within the item of my widget
This short tutorial provides the code snippets that helped me to solve the problem. From the start, we will rely on the Qt class that is able to test for emitted signals - QSignalSpy. It will help us to define whether the event happened or not.
Event within an item of the list widget
Assume we are given a QListWidget* listWidget;
and we want to test if the click was performed on the first list item. The below code snippet shows how to achieve it.
Event within an item’s button of the tree widget
Assume we are given a QTreeWidget* treeWidget;
, which has its own delegate where it is defined how to place buttons within it, and also how to process mouse events, for example, if the user presses on one of the buttons. We want to be able to simulate those mouse events and check if the necessary signals are emitted. The below snippet provides the basic idea on how to achieve it.
Note: I do not provide code reference for the widget’s delegate. As it can be seen from the snippet, the delegate contains a method to obtain a button’s coordinates. It also contains the signal which is emitted whenever that button is pressed. The treeWidget
class contains a method that retunrs a pointer on its delegate.
Leave a Comment