我正在尝试自动为 a 中的有效文件路径添加反斜杠,QLineEdit
用于显示 a 的当前路径QFileSystemModel
。
代码如下所示:
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/"
当我Enter从 lineEdit 中按下键时它可以正常工作,但是如果文本由 设置QCompleter
,我仍然会得到相同的调试输出,显示文本已更改,但斜线不会出现在 lineEdit 中。是否以QCompleter
某种方式取消了文本?