0

我正在尝试自动为 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某种方式取消了文本?

4

1 回答 1

0

这是一个 hack,但是将此连接添加到 QCompleter 会提供所需的行为。我认为在激活 QCompleter 的同时使用editingFinished() 时存在竞争条件,因此添加延迟允许在不被覆盖的情况下附加斜线。不利的一面是,该函数 know 每次更改都会被多次调用。我仍然对更好的解决方案感兴趣。

connect(fileSystemCompleter, activatedOverloadPtr, [&](QModelIndex index)
{
    QTimer* timer =  new QTimer;
    timer->setSingleShot(true);
    timer->setInterval(10);
    connect(timer, &QTimer::timeout, fileSystemPathEdit,  &QLineEdit::editingFinished);
    timer->start();
});
于 2014-10-02T13:17:26.273 回答