问题
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