Search code examples
c++qtqtestlib

QT close window by QTest in locked thread


I have a QT application and I want to test it with QTest. Shortly about what I wanna do: I have a Main Window, where the button Settings is located. If I click on this button, the QDialog is appeared. I want to test if this really happens

MainWindow mwindow;
QTest::mouseClick(mwindow->showButton, QtCore::Qt::LeftButton)

and then I would check for presence of text in new dialog and so on.

The dialog appears but - how do I close it within the test without closing it manually? And how do I test for text presence in it. If I got it right, I can't do anything in test while the dialog is shown.

What am I doing wrong?


Solution

  • You can use QTimer and QTest::keyClick().

    If your QMessgeBox's pointer is msgBox, in QTimer's timeout() slot,

    QTest::keyClick( msgBox, Qt::Key_Enter);
    

    Also, You can test for text with QCOMPARE macro.

    QCOMPARE( sourceText, targetText );
    

    APPEND

    I think QTimer::singleShot is a useful for solving your question.

    QMessageBox test;
    QDialog& dlg = test;
    QTimer::singleShot( 2000, &dlg, SLOT( close() ) );
    dlg.exec();
    

    In above code, test messagebox will close after 2 seconds. So, your code maybe..

    MainWindow mwindow;
    QDialog& dlg = mwindow;
    QTimer::singleShot( 2000, &dlg, SLOT( close() ) ); //or SLOT( quit() )?
    QTest::mouseClick(mwindow->showButton, QtCore::Qt::LeftButton)
    

    however, I've not tested. Also, try to read this articles. I hope this can help you.