本文介绍了Qt -Timers只能与以QThread开头的线程一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码是

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);

我在Here 1和Here 2之间得到一个qwarn

I get a qwarn between Here 1 and Here 2

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

我从 QObject :: startTimer了解到:定时器只能与以QThread开头的线程一起使用,当我对Qt类进行子类化并且该子类的成员之一不属于Qt层次结构时.我有从QObject继承的类ExampleTest,但仍然收到警告.如何避免此警告?

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?

推荐答案

警告可以使用更好的措辞-这不完全是QThread问题,而是事件循环问题. QThread会自动为您设置一个线程,但是这里只有一个主线程.

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. 使用 QEventLoop
  2. 手动创建一个
  3. 使用 QApplication (或其子类)为您创建了一个
  1. Create one manually with QEventLoop
  2. Have one created for you with QApplication (or its subclasses)

大多数应用程序将使用选项2.但是,您正在编写单元测试.在没有QApplication的情况下运行单元测试的原因是因为您指定了QTEST_APPLESS_MAIN.要引用文档:

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:

行为类似于QTEST_MAIN(),但不会实例化QApplication 对象.使用此宏可进行非常简单的独立非GUI测试.

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

强调我的.

因此,您所需要做的就是更改最后一行:

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

QTEST_APPLESS_MAIN(ExampleTest);

对此:

QTEST_MAIN(ExampleTest);

...这应该可以解决问题.

...and that should resolve the issue.

这篇关于Qt -Timers只能与以QThread开头的线程一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:51