Qt 人工鼠标点击不能正常工作

标签 qt qt4

可以在这里找到小玩具应用程序:http://gist.github.com/517445

我正在尝试向小部件发送人工鼠标事件,为此我使用了 QApplication::sendEvent,接下来我检查 ev.isAccepted() 并返回 False,甚至更糟!小部件我已发送事件以不处理它(它是日历小部件并且没有选择日期)并且我怀疑它是否会收到它,因为我可以看到 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->event(),对于 QCalendarWidget,它最终在 QAbstractScrollArea 中返回 false对于每个与鼠标相关的事件。

如果我是对的,那么如何模拟鼠标点击和按键操作?

最佳答案

解决方案是将事件发送到光标下的确切小部件,而不是其父级。

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

关于Qt 人工鼠标点击不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3451492/

相关文章:

c++ - Q_INVOKABLE可变函数

qt - 如何在同一台机器上使用不同版本的 Qt?

c++ - 将过剩与 Qt 联系起来

c++ - QTimeEdit 设置的最大值大于 23 :59:59

c++ - QML 对象属性的部分序列化

qt - 如何获取给定小部件的所有信号集?

Qt QTcpSocket : How to prevent dead lock in readyRead signal?

python - 为什么我的 QListView 在 IconMode 中是空的?

c++ - 在 Linux 上使用 C++ 进行 Artema 混合通信

c++ - Qt vtable错误