Qt Filesystembrowser: Как изменить корневой каталог и обновить вид - PullRequest
0 голосов
/ 26 апреля 2018

Я пытаюсь расширить пример qt filesystembrowser (Qt-Creator -> Welcome -> examples -> filesystembrowser). Я добавил кнопку к main.qml

Button {
    id: button
    x: 28
    y: 12
    text: qsTr("rootPath")
    onClicked: {
        view.model.setRoot("/home/myusername/test/")
        view.update()
    }
}

который должен изменить корневой каталог. Для этого я также добавил следующую функцию

Q_INVOKABLE QModelIndex setRoot(QString newPath)  {
    qInfo() <<"root path "<< this->rootPath();
    newPath.replace(0,7,"");
    setRootPath(newPath);
}

После двойного нажатия кнопки qInfo говорит мне, что корневой путь теперь /home/myusername/test/, но представление не обновляется. Что мне здесь не хватает?

1 Ответ

0 голосов
/ 26 апреля 2018

Проблема в том, что rootIndex из TreeView не изменяется, поскольку не обновляет представление.

Одним из решений является создание свойства rootIndex, которое возвращает индекс, помещенный в TreeView, его необходимо изменить при создании нового пути, так как он собирается перезаписать метод setRootPath и устранить свойство rootPathIndex, которое было отправлено через setContextProperty():

main.cpp

...

class DisplayFileSystemModel : public QFileSystemModel {
    Q_OBJECT
    Q_PROPERTY(QModelIndex rootIndex READ rootIndex WRITE setRootIndex NOTIFY rootIndexChanged)
public:
    ...    
    Q_INVOKABLE QModelIndex setRootPath(const QString &newPath){
       QModelIndex ix =  QFileSystemModel::setRootPath(newPath);
       setRootIndex(ix);
       return ix;
    }
    QModelIndex rootIndex() const{
        return mRootIndex;
    }
    void setRootIndex(const QModelIndex &rootIndex){
        if(mRootIndex == rootIndex)
            return;
        mRootIndex = rootIndex;
        Q_EMIT rootIndexChanged();
    }
    Q_SIGNAL void rootIndexChanged();
private:
    QModelIndex mRootIndex;
};

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QQmlApplicationEngine engine;
    qmlRegisterUncreatableType<DisplayFileSystemModel>("io.qt.examples.quick.controls.filesystembrowser", 1, 0,
                                                       "FileSystemModel", "Cannot create a FileSystemModel instance.");
    DisplayFileSystemModel *fsm = new DisplayFileSystemModel(&engine); // change
    fsm->setRootPath(QDir::homePath());
    fsm->setResolveSymlinks(true);
    engine.rootContext()->setContextProperty("fileSystemModel", fsm);
    engine.load(QUrl(QStringLiteral("qrc:///main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

#include "main.moc"

main.qml

    ...
    Row {
        ...

        Repeater {
            model: [ "rootPath", "None", "Single", "Extended", "Multi", "Contig."]
            Button {
                text: modelData
                exclusiveGroup: eg
                checkable: modelData != "rootPath"
                checked: index === 1
                onClicked: {
                    if(modelData != "rootPath")
                        view.selectionMode = index
                    else{
                        view.model.setRootPath("/home/myusername/test/")
                    }
                }
            }
        }
    }
...    
TreeView {
    id: view
    anchors.fill: parent
    anchors.margins: 2 * 12 + row.height
    model: fileSystemModel
    rootIndex: fileSystemModel.rootIndex //change
    selection: sel
...

Полный пример можно найти по следующей ссылке .

...