Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

I use QThread but UI is frozen



  • I need to collect information and count all files in directory. Having used QThread I hoped to "unfroze" UI during scanning. But it didnt work. FileScaner inherits QObject.

    class MainWindow : public QMainWindow
    {
        Q_OBJECT
    
    public:
        MainWindow(QWidget *parent = nullptr);
        ~MainWindow();
        QFileSystemModel model;
        QTreeView treeView;
        QThread thread;
        FileScaner scaner;
    }
    
    MainWindow::MainWindow(QWidget *parent)
        : QMainWindow(parent)
        , ui(new Ui::MainWindow){
    ...
        scaner.moveToThread(&thread);
        thread.start();
    }
    
    void MainWindow::on_pushButton_clicked()
    {
        QModelIndexList ind;
        ind=treeView.selectionModel()->selectedIndexes();
        scaner.scan(model.filePath(ind.last()));
    }
    
    Any ideas what's the problem?
    

  • Moderators

    You're calling scaner.scan directly on the ui thread so it's blocking. Moving an object to another thread doesn't mean its members are gonna be run there when invoked directly.

    To run it on the worker thread either use signal/slot or QMetaObejct::invokeMethod.

    Btw. you should really check if ind is not empty before calling last() on it.


Log in to reply