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

问题描述:

小玩具应用程序可以在这里找到:http://gist.github.com/517445Qt的人工点击鼠标不工作正常

我想送鼠标人工事件,窗口小部件,我使用的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调用小窗口>事件()这对于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); 
    } 

}

+1

你想解决什么问题?我无法想象需要模拟鼠标点击的很多情况。除了触发按钮,但他们有点击()。 – 2010-08-11 12:13:20

+3

我将Qt应用程序作为纹理嵌入到3D引擎中。我希望用户能够点击纹理并与应用进行交互。 – redbaron 2010-08-19 10:49:55