Use Qthread in a Qt Console application

  • Greetings.

    I wanted to know how to use QThread in a console application (an application without GUI). I don't know how and when to start the threads and general, how reconciling the work with threads and QCoreApplication.

    Thanks in advance for any help and/or suggestions.

  • Qt Champions 2017

    There is nothing specific about Threading in core application. "When to Use" thread itself is topic. You can goole around and you will get good number of topics. The same rule applies here as well.

  • "Here": is a good explanation on how to use QThread in general.

    If you need to start a thread immediately after application is started then put it to main()
    QCoreApplication a(argc, argv);

    // Here is thread initialization and start
    QThread* thread = new QThread;
    Worker* worker = new Worker();
    connect(worker, SIGNAL(error(QString)), this, SLOT(errorString(QString)));
    connect(thread, &QThread::started, worker, &Worker::process);
    connect(worker, &QThread::finished, thread, &QThread::quit);
    connect(worker, &QThread::finished, worker, &Worker::deleteLater);
    connect(thread, &QThread::finished, thread, &QThread::deleteLater);
    connect(thread, &QThread::finished, &a, &QCoreApplication::quit);

    // Start app event loop
    return a.exec();

Log in to reply