我正在尝试实现 Qt 单元测试,我想从 C++ 中“单击”QML 中的 qtquick 按钮。我能够成功地在我的一个 QML 对象的属性上使用 QCompare,test_case3
但我不知道如何在test_case4
. 我的文件在下面。
tst_case_1.cpp
void tst_case_1::test_case3()
{
QScopedPointer<MouseMemory> mouse(new MouseMemory);
QQmlEngine engine;
engine.rootContext()->setContextProperty("mouse", mouse.data());
QQmlComponent component(&engine, QUrl(QStringLiteral("qrc:/main.qml")));
QObject *object = component.create();
QQuickItem *clear = object->findChild<QQuickItem*>("clear");
QVariant tmp = clear->property("text");
QCOMPARE(tmp.toString(), "Clear2");
delete object;
}
void tst_case_1::test_case4()
{
QScopedPointer<MouseMemory> mouse(new MouseMemory);
QQmlEngine engine;
engine.rootContext()->setContextProperty("mouse", mouse.data());
QQmlComponent component(&engine, QUrl(QStringLiteral("qrc:/main.qml")));
QObject *object = component.create();
QQuickItem *clear = object->findChild<QQuickItem*>("clear");
/* INSERT CODE HERE
Implement QML QQuickItem Button click
/*
delete object;
}
main.qml
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
Window {
id: root
visible: true
width: 500
height: 500
Row {
id: tools
Button {
id: clear
objectName: "clear"
text: "Clear"
onClicked: {
canvas.clear()
}
}
Button {
id: save
text: "Save"
onClicked: {
mouse.save()
}
}
}
Canvas {
id: canvas
anchors.top: tools.bottom
width: 500
height: 500
property int lastX: 0
property int lastY: 0
function clear() {
var ctx = getContext("2d")
ctx.reset()
canvas.requestPaint()
mouse.clear()
}
onPaint: {
var ctx = getContext("2d")
ctx.lineWidth = 2
ctx.strokeStyle = color.red
ctx.beginPath()
ctx.moveTo(lastX, lastY)
lastX = area.mouseX
lastY = area.mouseY
ctx.lineTo(lastX, lastY)
ctx.stroke()
mouse.test()
mouse.add(lastX, lastY)
}
MouseArea {
id: area
anchors.fill: parent
onPressed: {
canvas.lastX = mouseX
canvas.lastY = mouseY
}
onPositionChanged: {
canvas.requestPaint()
}
}
}
}