rolly4444
rolly4444

Reputation: 67

how to add a new c++ class that inherits from QThread in a Qt widget application

I was trying to follow a youtube tutorial video from "voidRealm".

The instructor wanted to add a new class MyThread that inherits from QThread. He entered the new C++ class wizard, and filled it like this:

Old version of Qt Creator

Apparently, this wizard has changed in newer versions of Qt Creator. Here is what I get when I open it:

Newer version of Qt Creator

As you can see from the screenshots, the "Type Information" field is missing in the new version of Qt Creator. So, How can I add a new C++ class that inherits from QThread (taking into account that QThread inherits from QObject)?

Upvotes: 0

Views: 1169

Answers (1)

Mike
Mike

Reputation: 8355

Since the addition of the new wizard engine in Qt Creator 3.3.0 (see Qt blog post about Qt creator 3.3.0 release here), the "type information" option is no longer available for custom classes.

The new wizard engine allows users to write their custom wizards in JSON format. You can see the manual here.

Since all you need is just a basic C++ class (and no .ui form has to be generated), A quick workaround would be setting the the "Base Class" to QObject in the wizard.

screenshot

And after the new files are generated, you can edit the generated class to make it inherit from QThread instead of QObject. Since you are new to Qt, here is a list of what you need to do:

  1. Add #include <QThread> to mythread.h file.
  2. Change class MyThread : public QObject to class MyThread : public QThread in mythread.h file.
  3. in mythread.cpp file, change MyThread::MyThread(QObject *parent) : QObject(parent) to MyThread::MyThread(QObject *parent) : QThread(parent).

side notes:

  • This is just a quick workaround (It is not the best solution to the problem). A more general solution would be creating your own better custom wizard that supports inheriting from QThread.
  • Please note that there are many ways to do multi-threading in Qt without subclassing QThread. Worker objects are generally more preferable see here, You can also take a look at this post from the Qt blog.

Upvotes: 3

Related Questions