我的主要目标是编写一个可以模拟C ++中的qml按钮单击的测试用例。下面的代码片段完成了此操作,但它需要从qobject到qwindow的qobject_cast()
。是否有实现使用qobject的鼠标单击的选项?这是实现按钮单击的正确方法还是有更好的方法?main.qml
文件
import QtQuick 2.11
import QtQuick.Controls 2.2
import QtQuick.VirtualKeyboard 2.2
import QtQuick.Window 2.11
ApplicationWindow {
id: window
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Button {
id: button
objectName: "button"
x: 54
y: 118
text: qsTr("Button")
checkable: true
onClicked: {
button.text = qsTr("Clicked")
}
}
}
myClass.h
文件...
public:
void ClickItem(QObject*);
private slots:
void test_case1();
private:
QWindow *m_window;
...
myClass.cpp
文件void myClass::ClickItem(QObject* pItem)
{
int x = pItem->property("x").toInt();
int y = pItem->property("y").toInt();
QPoint location(x, y);
QTest::mouseClick(m_window, Qt::LeftButton, Qt::NoModifier, location);
}
void myClass::test_case1()
{
QObject *engine;
QQmlComponent component(&engine, QUrl(QStringLiteral("qrc:../app/Display.qml")));
object = component.create();
m_window = qobject_case<QWindow *>(object);
QObject *item = object->findChild<QObject*>("button");
if (item) {
myClass::ClickItem(item);
QVariant value = item->property("text");
QCOMPARE(value.toString(), QString("Clicked"));
} else {
qDebug() << "Did not work";
}
}
最佳答案
这似乎为我工作:
QObject* obj = view.findChild<QObject*>("button");
QEvent evtPress(QEvent::MouseButtonPress);
QEvent evtRelease(QEvent::MouseButtonRelease);
obj->event(&evtPress);
obj->event(&evtRelease);
关于c++ - 在c++中模拟qml按钮单击的更好方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54068360/