Why does my treeview in GUI with QFileSystemModel sometimes freezing when I copying file in separate thread (Qt)?

做~自己de王妃 提交于 2019-12-11 16:12:12

问题


Here is my Model, that inherits QFileSystemModel

class MyFileSysModel : public QFileSystemModel
{
    Q_OBJECT
public:
    MyFileSysModel( QObject *parent = 0);
    Qt::ItemFlags  flags(const QModelIndex &index) const;
    bool dropMimeData(const QMimeData *data,
    Qt::DropActions supportedDropActions() const;
};

in MainWindow I created model and initializied treeview

 MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        model = new MyFileSysModel(this);
        model->setRootPath("/");
       ui->treeView->setModel(model);

         ui->treeView->setSelectionMode(QAbstractItemView::ExtendedSelection);
         ui->treeView->setDragEnabled(true);
         ui->treeView->viewport()->setAcceptDrops(true);
         ui->treeView->setDropIndicatorShown(true);
         ui->treeView->setDragDropMode(QAbstractItemView::DragDrop);
         ui->treeView->setAcceptDrops(true);
         ui->treeView->setDefaultDropAction(Qt::MoveAction);
    }

When user drag and drop file it is copying to other directory in separate thread

 class MoveFilesTask : public QObject, QRunnable
    {
        Q_OBJECT
        void run()
        {
            QFile source("source_file_name");
            source.open(QIODevice::ReadOnly);
            QFile destination("some_destination");
            destination.open(QIODevice::WriteOnly);
            QByteArray buffer;
            int chunksize = 200;

            while(!(buffer = source.read(chunksize)).isEmpty())
            {
                destination.write(buffer);
            }
            destination.close();
            source.close();
        }
       void MoveFilesTask::runFilesTransfer(QString source, QString destination)
        {
           QThreadPool::globalInstance()->start(this);
        }
};

File is copying but the GUI in MainWindow with my treeview doesn't work well, it is freezing and blocking sometimes. I think this is because my model updating very often. How can I solve this and prevent updating very often ?


回答1:


QFileSystemModel lists directories on a background thread to avoid blocking the UI. However, once it gets a list of updates in QFileSystemModelPrivate::_q_fileSystemChanged it then fetches the icons for the file in the main thread using QFileInfoGatherer::getInfo() which in turn calls QFileIconProvider::icon(QFileInfo).

You should know Models are not using a different thread. they're using main thread.

If you want to use Model, use a loading animation (loading gif) in your UI to show progressing time.



来源:https://stackoverflow.com/questions/45252055/why-does-my-treeview-in-gui-with-qfilesystemmodel-sometimes-freezing-when-i-copy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!