2014-10-01 3 views
0

QFileSystemModel의 현재 경로를 표시하는 데 사용되는 QLineEdit에 유효한 파일 경로에 백 슬래시를 자동으로 추가하려고합니다. 다음과 같이QLineEdit : 백 슬래시를 디렉토리 이름에 자동으로 추가합니다.

코드는 같습니다

fileSystem = new QFileSystemModel; 
fileSystem->setRootPath(QObject::tr("C:\\")); 

QCompleter* fileSystemCompleter = new QCompleter(fileSystem); 
fileSystemCompleter->setCaseSensitivity(Qt::CaseInsensitive); 

fileTree = new QDeselectableTreeView(); 
fileTree->setModel(fileSystem); 
fileTree->setRootIndex(fileSystem->index(fileSystem->rootPath())); 
connect(fileTree, &QTreeView::clicked, [&] (QModelIndex index) 
{ 
    QString toAppend(""); 
    if (fileSystem->isDir(index)) 
    { 
     toAppend = '/'; 
    } 
    fileSystemPathEdit->setText(fileSystem->filePath(index)+toAppend); 
}); 

// path line edit 
fileSystemPathEdit = new QLineEdit(fileSystem->rootPath()); 
fileSystemPathEdit->setPlaceholderText("Path..."); 
fileSystemPathEdit->setCompleter(fileSystemCompleter); 
connect(fileSystemPathEdit, &QLineEdit::editingFinished, [&]() 
{ 
    // jump to that location 
    qDebug() << fileSystemPathEdit->text(); 
    QModelIndex index = fileSystem->index(fileSystemPathEdit->text()); 
    qDebug() << index; 
    fileTree->setExpanded(index,true); 
    fileTree->setCurrentIndex(index); 
    // CLOSE IF EMPTY 
    if (fileSystemPathEdit->text().isEmpty()) 
    { 
     fileTree->collapseAll(); 
     fileSystemPathEdit->setText(fileSystem->rootPath()); 
    } 
    // append slashes to dirs 
    else if (fileSystem->isDir(index) && index.isValid()) 
    { 
     qDebug() << "it's a dir"; 
     if (!fileSystemPathEdit->text().endsWith('/',Qt::CaseInsensitive)) 
     { 
      qDebug() << "added slash"; 
      fileSystemPathEdit->setText(fileSystemPathEdit->text().append('/')); 
      qDebug() << fileSystemPathEdit->text(); 
     } 
    } 
    this->update(); 
}); 

코드를 실행할 때 나는 다음과 같은 출력을 얻을 :

"C:/export/home" 
QModelIndex(0,0,0x3adb840,QFileSystemModel(0x1d9b7c0)) 
it's a dir 
added slash 
"C:/export/home/" 

나는 가 lineEdit 내에서 Enter 키를 누르면 그것은 작품을 좋아, 그러나 텍스트가 QCompleter에 의해 설정되면 텍스트가 변경되었음을 나타내는 동일한 디버그 출력을 얻지 만 라인 에디터에는 슬래시가 나타나지 않습니다. QCompleter이 어떻게 든 텍스트의 설정을 해제합니까?

+0

완료 후 Enter 키를 누르면 어떻게됩니까? 그러면 슬래시가 추가됩니까? – Ezee

+0

죄송합니다. 관련이 없지만 최종 신청서에서 "C : \\"를 번역해야합니까? Windows 루트 경로는 사용자의 언어와 관련이 없습니다. – Antwane

+0

아니요, Qt 코드를 작성할 때 습관 일뿐입니다. 어쨌든 C 드라이브는 최종 설정 앱인 자리 표시 자일 뿐이며 구성 설정이됩니다. –

답변

0

이것은 해킹이지만이 연결을 QCompleter에 추가하면 원하는 동작을 제공합니다. QCompleter가 활성화 될 때 editingFinished()를 사용할 때 경쟁 조건이 있다고 생각합니다. 따라서 지연을 추가하면 재정의하지 않고 슬래시를 추가 할 수 있습니다. 아래쪽에서, 그 기능은 변화마다 여러 번 호출된다는 것을 알게됩니다. 나는 여전히 더 나은 해결책에 관심이있다.

connect(fileSystemCompleter, activatedOverloadPtr, [&](QModelIndex index) 
{ 
    QTimer* timer = new QTimer; 
    timer->setSingleShot(true); 
    timer->setInterval(10); 
    connect(timer, &QTimer::timeout, fileSystemPathEdit, &QLineEdit::editingFinished); 
    timer->start(); 
}); 
관련 문제