我想对我的Qt应用程序做一个基本的自动化测试。它记录鼠标事件并将它们写入文件(f.e. mousepress(300,400))。当开始自动化时,它从文件读取坐标,发送适当的鼠标事件,并与先前保存的屏幕截图进行像素比较。如何通过将事件发布到Qt事件系统来模拟鼠标点击?
目前,我有一个覆盖小部件,跨越应用程序,并有透明的鼠标事件。它所做的就是跟踪坐标。 重新读取数据时,该覆盖图会在鼠标按下位置绘制一个矩形。 发送mousePressEvents到Qt的事件系统时需要帮助。它在正确的位置绘制点,但从未实际进行物理点击。 有没有办法做到这一点与Qt或我必须使用Window的SendInput()?
有没有办法暂停并等待鼠标事件结束?我需要知道事件何时完成才能开始逐像素比较。
Widget::Widget(QWidget *parent)
: QFrame(parent)
, mPoint(QPoint(0,0))
{
setWindowFlags(Qt::WindowStaysOnTopHint);
setStyleSheet("background-color: rgba(0, 0,255, 2%);");
setAttribute(Qt::WA_TransparentForMouseEvents, true);
setGeometry(parent->geometry());
...
}
void Widget::run()
{
QFile file("coordinates.txt", NULL);
if(!file.open(QIODevice::ReadOnly))
return;
QTextStream in(&file);
int i = 0;
while (!in.atEnd())
{
QString line = in.readLine();
if(line.startsWith("mousepress"))
{
int startIndex = line.indexOf('(');
int endIndex = line.indexOf(')');
QString coord = line.mid(startIndex+1, line.size() - startIndex - 2);
QStringList nbr = coord.split(',');
mPoint = QPoint(nbr[0].toInt(), nbr[1].toInt());
QWidget *receiver = QApplication::widgetAt(mPoint);
QMouseEvent *event = new QMouseEvent(QEvent::MouseButtonPress, mPoint, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
QCoreApplication::postEvent(receiver, event); // same result with sendEvent()
QCoreApplication::processEvents();
update();
// wait till the event finished, then continue with next point
}
}
}
void Widget::paintEvent(QPaintEvent *event)
{
QPainter p(this);
QPen pen;
pen.setBrush(Qt::NoBrush);
if(!mPoint.isNull())
{
pen.setColor(Qt::red);
pen.setWidth(2);
p.setPen(pen);
p.drawRoundRect(mPoint.x(), mPoint.y(), 10, 10, 25, 25);
p.drawText(mPoint, QString::number(mPoint.x()) + ", " + QString::number(mPoint.y()));
}
}
[编辑]
我跟着ddriver的建议,并就一些修改后的作品:我保存全局和局部位置的文件,发送到QMouseEvent。
在做屏幕截图并将其与保存的图像进行比较之前,我怎么能确定鼠标点击已完成?
void Widget::DoStep()
{
if(!mInStream.atEnd())
{
QString line = mInStream.readLine();
if(line.startsWith("MouseButtonPress"))
{
QPoint pos = parseGlobalPos();
QPoint localPos = parseLocalPos();
QWidget *receiver = QApplication::widgetAt(pos);
QMouseEvent *event = new QMouseEvent(QEvent::MouseButtonPress,localPos, pos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
QApplication::postEvent(receiver, event);
QMouseEvent *eventRelease = new QMouseEvent(QEvent::MouseButtonRelease, localPos, pos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
QApplication::postEvent(receiver, eventRelease);
// after successful click, take screenshot and compare them
}
}
if (!mInStream.atEnd())
QMetaObject::invokeMethod(this, "DoStep", Qt::QueuedConnection);
else
file.close();
}
这可能无法完全解决这个问题,但是,您提交MouseButtonPress的事件,但你缺少一个相应的MouseButtonRelease。另外,我建议不要循环并等待事件完成,而应该为每个事件使用单个QTimer,并让主循环继续运行,而不要求助于调用processEvents。 – TheDarkKnight
谢谢,我试图发布一个额外的MouseButtonRelease事件,但没有奏效。 – user2246120
我不太清楚我的理解你的QTimer的想法。 QTimer :: singleShot(0,receiver,SlotSendEvent());无法将坐标传递给插槽。你是什么意思? – user2246120