moveToThread vs deriving from QThread in Qt

前端 未结 4 1020
南笙
南笙 2021-02-01 17:07

When should moveToThread be preferred over subclassing QThread?

This link shows that both methods work. On what basis should I decide what to u

4条回答
  •  太阳男子
    2021-02-01 17:21

    Simple answer is ALWAYS. When you move object to thread:

    • it is easy to write test for code
    • it is easy to refactor code (you can use thread but you don't have to).
    • you do not mix functionality of thread with business logic
    • there is no problem with object lifetime

    When you subclass QThread

    • it is harder to write test
    • object clean up process can get very confusing leading to strange errors.

    There is full description of the problem from Qt blog: You’re doing it wrong….

    QtConcurrent::run is also very handy.

    Please remember that by default slots are trying to jump between treads when signal is send from other thread object is assigned to. For details see documentation of Qt::ConnectionType.

提交回复
热议问题