Qt人工鼠标点击无法正常工作

时间:2010-08-10 17:05:19

标签: qt qt4

可在此处找到小型玩具应用程序:http://gist.github.com/517445

我正在尝试将人工鼠标事件发送到窗口小部件,我使用 QApplication :: sendEvent ,然后我检查ev.isAccepted()并返回False,更糟! Widget我发送的事件并没有处理它(它是日历widged并没有选择日期)我怀疑它甚至收到它,因为我可以看到mouseEventPressed是如何在父窗口小部件上启动的。

Qt代码:

#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-&gt; event(),其中QCalendarWidget最终在 QAbstractScrollArea 中返回每个与鼠标相关的事件都是假的。

如果我是对的,那么我该如何模仿鼠标点击和按键呢?

1 个答案:

答案 0 :(得分:4)

解决方案是将事件发送到光标下的精确窗口小部件,而不是父窗口。

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

}