Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt -Timers can only be used with threads started with QThread

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?

like image 626
Vinoth Avatar asked May 19 '15 20:05

Vinoth


1 Answers

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.

like image 79
MrEricSir Avatar answered Sep 29 '22 08:09

MrEricSir