我正在尝试自动为QLineEdit
中的有效文件路径添加反斜杠,用于显示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/"
当我从lineEdit中按 Enter 键时它工作正常,但是如果文本是由QCompleter
设置的,我仍然得到相同的调试输出,显示文本有已更改,但斜线不会出现在lineEdit中。 QCompleter
是否以某种方式取消了文本?
答案 0 :(得分:0)
这是一个hack,但是将此连接添加到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();
});