K
K
katavagner2022-02-16 19:03:44
Qt
katavagner, 2022-02-16 19:03:44

Why does the GUI hang in Qt?

There is a main class in which all elements are registered. I write in the constructor so that the thread_import method works in another thread:

OneThing::OneThing(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::OneThing)
{
     // какой-то код
    qDebug() << "MAIN THREAD: " << QThread::currentThread();
    QFuture<bool> future = QtConcurrent::run(this, &OneThing::thread_import);
    QFutureWatcher<bool> watcher;
    watcher.setFuture(future);
}

The thread_import method looks like this:

bool OneThing::thread_import() {
    qDebug() << "IMPORT THREAD: " << QThread::currentThread();

    connect(ui->button_import, &QPushButton::clicked, this, [this]() {
                int count = 0;
        qDebug() << "CONNECT THREAD: " << QThread::currentThread();
                while (true) {
                    qDebug() << "THREAD: " << count;
                    count++;
                    QThread::sleep(1);
                }
    });

    return true;
}


Conclusion:
MAIN THREAD:  QThread(0x1fd1f88)
IMPORT THREAD:  QThread(0x41bfbe8, name = "Thread (pooled)")
CONNECT THREAD:  QThread(0x1fd1f88)


That is, a new thread is created, and if you place an infinite loop in the thread_import method, and not in the connect function slot, then the GUI will not freeze, since the calculations are performed in another thread.

I can't figure out how to make the slot run in a new thread when the button is clicked.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
redcircle, 2022-02-17
@katavagner

Move QtConcurrent::run inside the [this]() {} lambda and call connect on the main thread.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question