问题描述
这是我的模型,它继承了QFileSystemModel
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;
};
在MainWindow中,我创建了模型并初始化了树视图
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);
}
};
文件正在复制,但是MainWindow中带有我的Treeview的GUI不能正常工作,有时会冻结和阻塞.我认为这是因为我的模型经常更新.我该如何解决这个问题并防止经常更新?
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 ?
推荐答案
QFileSystemModel
在后台线程上列出目录,以避免阻塞UI.但是,一旦它在QFileSystemModelPrivate::_q_fileSystemChanged
中获取更新列表,便会使用QFileInfoGatherer::getInfo()
提取主线程中文件的图标,该文件又调用QFileIconProvider::icon(QFileInfo)
.
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.
如果要使用模型,请在用户界面中使用加载动画(加载gif)以显示进度.
If you want to use Model, use a loading animation (loading gif) in your UI to show progressing time.
这篇关于为什么在单独线程(Qt)中复制文件时,带有QFileSystemModel的GUI中的树形视图有时会冻结?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!