tags:

views:

37

answers:

1

Small toy app can be found here: http://gist.github.com/517445

I am trying to send artificial mouse event to widget and I use QApplication::sendEvent for that, next I check ev.isAccepted() and it returns False, even worse! Widget I've sent event to doesnt handle it (it is calendar widged and no date is picked) and I am in doubt that it even receives it, because I can see how mouseEventPressed is fired up on parent widget.

Qt Code:

#include "calendar.h"

Calendar::Calendar(QWidget *parent) :
    QWidget(parent)
{
    qCal = new QCalendarWidget;
    qBtn = new QPushButton(tr("Press me"));

    connect(qBtn, SIGNAL(clicked()), this, SLOT(testCustomClick()));

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(qCal);
    layout->addWidget(qBtn);

    setLayout(layout);
    qDebug() << "Date:" << QDate::currentDate();
 }

 Calendar::~Calendar()
 {
 }

void Calendar::testCustomClick()
{
    QMouseEvent qm2(QEvent::MouseButtonPress, QPoint(qCal->width()/2,
         qCal->height()/2), Qt::LeftButton , Qt::LeftButton, Qt::NoModifier);
    QApplication::sendEvent(qCal, &qm2);

    //this one is always False
    qDebug() << "isAccepted: " << qm2.isAccepted();
}


void Calendar::mousePressEvent(QMouseEvent* ev)
{
    //this is executed even for QMouseEvent which sended to qCal =((
    //if we click on qCal with real mouse it is not executed
    qDebug() << "mouse event: " << ev << "x=" << ev->x() <<" y=" << ev->y();
    QWidget::mousePressEvent(ev);
}

According to source code QApplication::sendEvent calls widget->event() which for QCalendarWidget is ended up in QAbstractScrollArea which returns false for every mouse related event.

If I am right, then how can I emulate mouse clicks and keypresses?

A: 

Solution is to send event to exact widget under cursor, not to its parents.

void Calendar::testCustomClick()
{
   QPoint pos(qCal->width()/2,qCal->height()/2);
   QWidget *w = qApp->widgetAt(qCal->mapToGlobal(pos));
   qDebug() << "widget under point of click: " << w;

   {
   QMouseEvent qm2(QEvent::MouseButtonPress, pos, Qt::LeftButton , Qt::LeftButton,    Qt::NoModifier);
   QApplication::sendEvent(w, &qm2);
   }
   {
   QMouseEvent qm2(QEvent::MouseButtonRelease, pos, Qt::LeftButton , Qt::LeftButton,    Qt::NoModifier);
   QApplication::sendEvent(w, &qm2);
   }

}

redbaron
what problem do you want to solve? I can't think of so many cases where one needs to emulate mouse clicks. Except maybe for triggering buttons, but they have click().
Frank
I am embedding Qt application as a texture in 3d engine. I'd like users to be able to click on texture and interact with app.
redbaron