다른 프로세스를 통해 파일이 변경된 후 QTreeView에서 QFileSystemModel을 새로 고치는 방법은 무엇입니까?
-
24-12-2019 - |
문제
나는 QTreeView
와 QFileSystemModel
모델로.파일과 디렉터리가 올바르게 로드됩니다.
내 애플리케이션 워크플로에서는 다른 프로세스가 파일 시스템의 파일을 복사하고 덮어씁니다.
그러나 내 QTreeView
덮어쓴 파일의 항목/행을 업데이트하지 않습니다(예:파일의 크기 및 lastModified 값은 새 값으로 업데이트되지 않습니다.
파일 경로를 사용하면 FileInfo
업데이트된 lastModified 값이 있습니다.그런데 그걸 이용해서 같은 길 잡기 위해 QModelIndex
행의 lastModified 값 중 이전 값이 반환됩니다.
나는 몇 가지(아래 참조)를 시도했지만 아무 소용이 없었습니다.
이 문제를 해결하는 방법을 알고 있다면 알려주시기 바랍니다.정말 감사합니다!:)
// ... 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();
[편집 - 애플리케이션 워크플로를 시뮬레이션하는 단계 추가]
다음은 문제를 모방할 수 있는 단계라고 생각합니다.
재현 단계:
QFileSystemModel을 모델로 사용하는 간단한 QTreeView를 설정합니다.
루트 경로를 다음 디렉터리로 설정합니다.
Root
텍스트 파일을 생성하고,
Test.txt
내부Root
디렉토리애플리케이션을 로드하고 그 안에서
Test.txt
파일의 마지막 수정 날짜 에서Root
디렉토리.이 응용 프로그램 창을 열어 두십시오.
복사
Test.txt
에게 다른 디렉토리, 말하자면Temp
파일을 수정하고 저장하세요.
Temp
복사 및 바꾸다
Test.txt
파일을 덮어쓰려면Root
디렉토리관찰하다 마지막 수정 날짜 신청 창에서
결과:그만큼 마지막 수정 날짜 업데이트되지 않았습니다
추가된 샘플:
#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");