简体   繁体   中英

How to add CheckBox on QTreeView + QFileSystemModel

I want to select some different folders in the treeview. There are two solution in QT like this: 在此处输入图片说明

  1. QTreeView + QFileSystemModel, But how add the treebox in it? I dotn't know at all. In the same time, QFileSystemModel is asychronised, so after you choose a folder, then expand the directory, you will find the sub-folder were not choosen. How can I solve the this problem?

  2. QTreeView + QDirModel, there is a good model and it work well: http://www.programmershare.com/2041913/ But QDirModel is synchronised. So we have to wait a long time when choose a big folder. We can accept a long time, but how I can know the selection is finished?

Thanks anyway.

Your example should be tweaked a bit to use QFileSystemModel .

The trick is to declare the checkedIndexes set as mutable and update it inside the CFileSystemModel::data method.

QVariant CFileSystemModel::data(const QModelIndex &index, int role) const
{
    if(role == Qt::CheckStateRole)
    {
        if (checkedIndexes.contains(index))
        {
            return checkedIndexes.contains(index) ? Qt::Checked : Qt::Unchecked;
        }
        else
        {
            int checked = Qt::Unchecked;

            QModelIndex parent = index.parent();
            while (parent.isValid())
            {
                if (checkedIndexes.contains(parent))
                {
                    checked = Qt::Checked;
                    break;
                }

                parent = parent.parent();
            }

            if (checked == Qt::Checked)
            {
                checkedIndexes.insert(parent);
            }

            return checked;
        }
    }
    else
    {
        return QFileSystemModel::data(index, role);
    }
}

When you open a directory node in a view, QFileSystemModel starts to load new contents. After they are loaded, the view retieves new data using CFileSystemModel::data function, which checks if new nodes anchestors were checked and returns proper Qt::CheckStateRole value (and also updates the checkedIndexes set).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM