Как обновить QFileSystemModel в QTreeView после изменения файлов с помощью другого процесса?
-
24-12-2019 - |
Вопрос
У меня есть QTreeView
с помощью QFileSystemModel
в качестве модели.Файлы и каталоги загружаются корректно.
В рабочем процессе моего приложения другой процесс копирует и перезаписывает файлы в файловой системе.
Однако мой QTreeView
не обновляет элемент / строку для перезаписанного файла (например:размер и последние измененные значения для файла не обновляются до новых значений).
Используя путь к файлу, я могу получить FileInfo
это ДЕЙСТВИТЕЛЬНО имеет обновленное значение LastModified.Однако, используя это тот же путь чтобы схватить QModelIndex
последнее измененное значение строки приводит к тому, что она возвращает старое значение.
Я попробовал несколько способов (см. Ниже), но безрезультатно.
ПОЖАЛУЙСТА, дайте мне знать, если вы знаете, как это решить.Большое спасибо!:)
// ... at this point the file system has been updated and the file
// has new values for things like last modified date
QFileInfo *updatedFile = new QFileInfo( filePath );
QModelIndex indexOfFileName = myFileTreeView->myFileSystemModel->index( filePath );
QModelIndex indexOfLastModifiedDate = myFileTreeView->myFileSystemModel->index( filePath, lastModifiedColumnIndex );
// attempts to kick the QFileSystemModel and QTreeView to update the model values
// a collection from the internet :)
emit myFileTreeView->dataChanged( indexOfFileName, indexOfLastModifiedDate );
emit myFileTreeView->myFileSystemModel->dataChanged( indexOfFileName, indexOfLastModifiedDate );
myTreeView->repaint();
myTreeView->update( indexOfLastModifiedDate );
myTreeView->viewport()->update();
// looking to see if values changed
QModelIndex newIndexOfLastModifiedDate = myTreeView->myFileSystemModel->index( filePath, lastModifiedColumnIndex );
// this shows the correct row and column for the index, so the index looks correct
qDebug() << "newIndexOfLastModifiedDate: " << newIndexOfLastModifiedDate;
// does not have new value
qDebug() << "newIndexOfLastModifiedDate.data(): " << newIndexOfLastModifiedDate->data();
// has new value
qDebug() << "fileInfo.lastModified(): " << updatedFile->lastModified();
[ПРАВКА - добавление шагов для имитации рабочего процесса приложения]
Следующие, я полагаю, шаги, которые могут имитировать проблему.
Шаги по воспроизведению:
Настройте простой QTreeView, который использует QFileSystemModel в качестве своей модели.
Задайте корневой путь к каталогу с именем
Root
Создайте текстовый файл,
Test.txt
внутриRoot
режЗагрузите приложение и понаблюдайте в нем за
Test.txt
файлы Дата последнего изменения вRoot
реж.Держите окно этого приложения открытым.
Копировать
Test.txt
к a другой справочник, скажемTemp
Измените файл и сохраните в
Temp
Копировать и Заменить
Test.txt
чтобы перезаписать файл вRoot
режНаблюдайте за Дата последнего изменения в окне приложения
Результат:Тот Самый Дата последнего изменения не обновляется
ДОБАВЛЕННЫЙ SAPMLE:
#include <QApplication>
#include <QFileSystemModel>
#include <QFile>
#include <QFileInfo>
#include <QTimer>
#include <QDebug>
#include <QTreeView>
#include <QDateTime>
// Globals
QFileSystemModel *model = NULL;
const QString name = "test.txt";
const int delayOffset = 1000;
// Interface
void onDataChanged( const QModelIndex& topLeft, const QModelIndex& bottomRight, const QVector< int >& roles );
void clean();
void doCreateFile();
void doUpdateFile();
void doTest();
// Implementation
int main( int argc, char *argv[] )
{
QApplication a( argc, argv );
int delay = 0;
// Clean
clean();
// Init model
const QString rootPath = QCoreApplication::applicationDirPath();
model = new QFileSystemModel( &a );
model->setRootPath( rootPath );
QObject::connect( model, &QFileSystemModel::dataChanged, &onDataChanged );
// Init file actions
delay += delayOffset * 2;
QTimer tCreate;
tCreate.setSingleShot( true );
tCreate.setInterval( delay );
QObject::connect( &tCreate, &QTimer::timeout, &doCreateFile );
delay += delayOffset * 4;
QTimer tUpdate;
tUpdate.setSingleShot( true );
tUpdate.setInterval( delay );
QObject::connect( &tUpdate, &QTimer::timeout, &doUpdateFile );
// GUI
QTreeView w;
w.setModel( model );
w.setRootIndex( model->index( rootPath ) );
w.show();
w.expandAll();
qDebug() << "Start";
tCreate.start();
tUpdate.start();
return a.exec();
}
void onDataChanged( const QModelIndex& topLeft, const QModelIndex& bottomRight, const QVector< int >& roles )
{
qDebug() << "Model changed";
}
void clean()
{
const QString path = QString( "%1/%2" ).arg( QCoreApplication::applicationDirPath() ).arg( name );
QFile f( path );
if ( f.exists() )
f.remove();
}
void doCreateFile()
{
const QString path = QString( "%1/%2" ).arg( QCoreApplication::applicationDirPath() ).arg( name );
QFile f( path );
if ( !f.open( QIODevice::WriteOnly ) )
{
qDebug() << "Could not create file";
return ;
}
f.write( "Preved" );
f.close();
qDebug() << "File created";
doTest();
}
void doUpdateFile()
{
const QString path = QString( "%1/%2" ).arg( QCoreApplication::applicationDirPath() ).arg( name );
QFile f( path );
if ( !f.open( QIODevice::Append ) )
{
qDebug() << "Could not open file for modification";
return ;
}
f.write( " medved" );
f.close();
qDebug() << "File updated";
doTest();
}
void doTest()
{
const QString path = QString( "%1/%2" ).arg( QCoreApplication::applicationDirPath() ).arg( name );
QFileInfo info( path );
qDebug() << "Last modified (real): " << info.lastModified().toString( "hh:mm:ss" );
qDebug() << "Last modified (model): " << model->lastModified( model->index( path ) ).toString( "hh:mm:ss" );
}
Решение
Вы должны использовать QFileSystemWatcher
отслеживать события для каждого файла, когда необходимо обновить вашу модель.
QFileSystemWatcher
не отслеживает события из-за проблем с производительностью.Это известная проблема.Таким образом, вы можете создать свою собственную модель и / или использовать предложенный обходной путь:
model.setRootPath("");
model.setRootPath("the_folder_you_want_to_update");