8

My code is

class ExampleTest : public QObject
{
    Q_OBJECT

public:
    ExampleTest() {}

private Q_SLOTS:
   void DoAllExampleTests();
};

void ExampleTest::DoAllExampleTests()
{
    QProcess p;

    p.start( "cmd /c wmic path Win32_usbcontrollerdevice|grep VID_1004" );
    qDebug() << "Here 1";
    QVERIFY( TRUE == p.waitForFinished() );
    qDebug() << "Here 2";
}

QTEST_APPLESS_MAIN(ExampleTest);

I get a qwarn between Here 1 and Here 2

QObject::startTimer: Timers can only be used with threads started with QThread

I learnt from QObject::startTimer: Timers can only be used with threads started with QThread that when I subclass a Qt class and one of the members of the subclass is not part of the Qt hierarchy. I have the class ExampleTest inherited from QObject, but still I get the warning. How to avoid this warning?

Community
  • 1
  • 1
Vinoth
  • 301
  • 5
  • 12

1 Answers1

15

The warning could use better wording -- it's not exactly a QThread issue, it's an event loop issue. QThread automatically sets one up for you, but here you only have a main thread.

There's two ways to create an event loop in your main thread:

  1. Create one manually with QEventLoop
  2. Have one created for you with QApplication (or its subclasses)

Most applications will use option 2. However, you're writing a unit test. The reason your unit test is running without a QApplication is because you specified QTEST_APPLESS_MAIN. To quote the documentation:

Implements a main() function that executes all tests in TestClass.

Behaves like QTEST_MAIN(), but doesn't instantiate a QApplication object. Use this macro for really simple stand-alone non-GUI tests.

Emphasis mine.

So all you need to do is change the last line from this:

QTEST_APPLESS_MAIN(ExampleTest);

to this:

QTEST_MAIN(ExampleTest);

...and that should resolve the issue.

MrEricSir
  • 8,044
  • 4
  • 30
  • 35
  • and then run the QTest with `make check TESTARGS="-platform offscreen"`, and remove the `QT -= gui` line from the .pro project file which QtCreator puts in there for you. If you are using SUBDIRS style unit test project, then you will need to change all subprojects to QTEST_MAIN to cope with the `-platform` command line parameter – Mark Ch Mar 29 '17 at 12:32
  • For applications not linking with QtGui there is QTEST_GUILESS_MAIN. It's in-between QTEST_APPLESS_MAIN and QTEST_MAIN. – textshell Jul 30 '22 at 19:54