Search code examples
c++qtqplaintexteditqtest

QPlainTextEdit Mouse Events: Right/Middle Click Not Accepted in QTest


I've subclassed QPlainTextEdit but haven't overridden the mouse press/move/release events. When I simulate a left-click on the widget in my Qt unit test, the cursor successfully moves to the clicked position. However, when I simulate a right-click or middle-click at the same position, I receive the following warnings:

Mouse event "MousePress" not accepted by receiving widget
Mouse event "MouseRelease" not accepted by receiving widget

Here's my code:

widget->setMouseTracking(true);
widget->setFocus();
QCoreApplication::processEvents();
QTest::qWait(1000); // This is only for testing, just to be safe

// This works even when passing a QPoint to a random position within the widget (the cursor position moves)
QTest::mouseClick(widget, Qt::LeftButton, Qt::NoModifier, widget->cursorRect().center());

// This does not work, and the warnings are printed
QTest::mouseClick(widget, Qt::RightButton, Qt::NoModifier, widget->cursorRect().center());

Does anyone have suggestions on why this is happening and how I can resolve it?

EDIT: Qt version 5.15.2

EDIT 2: I tried using a QPlainTextEdit object without subclassing it. Same. I also tried overriding mousePress/mouseRelease and I can see that the functions are not called. The widget does not get the events.


Solution

  • I figured it out. The key was to send the event not to the widget directly, but to its viewport.

    QTest::mouseClick(widget->viewport(), Qt::RightButton, Qt::NoModifier, widget->cursorRect().center());
    

    I hope this helps others.