Qt Artificial mouse clicks do not work properly

A small toy application can be found here: http://gist.github.com/517445

I try to send an artificial mouse event to the widget, and for this I use QApplication :: sendEvent , then I check ev.isAccepted () and returns False, which is even worse! The widget to which I sent the event does not process it (it is changed on the calendar, but the date is not selected), and I doubt that it even receives it, because I see how mouseEventPressed is launched on the parent widgets.

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);
}

QApplication:: sendEvent widget- > event(), QCalendarWidget QAbstractScrollArea, false , .

, ?

+3
1

- , .

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);
   }

}

+4

Source: https://habr.com/ru/post/1758970/


All Articles