qlistview使用自定义模型的复选框

时间:2011-03-18 03:51:30

标签: c++ checkbox qlistview

我已经将filesystemmodel子类化为listview中的复选框,这样可以正常工作。我的问题是每当我点击某个项目时该项目的文本消失,当我点击另一个项目时,之前所选项目的文本变为可见。任何人都可以告诉我背后的原因。

这是我实施的代码。

请告诉我这里缺少什么, 感谢

#include "custommodel.h"
#include <iostream>

using namespace std;

CustomModel::CustomModel()
{

}

QVariant CustomModel::data(const QModelIndex& index, int role) const
{
    QModelIndex parent=this->parent(index);
    if(role == Qt::DecorationRole)
    {
        if(this->filePath(parent)=="")
        {
            return QIcon(":/Icons/HardDisk.png");
        }

        else if(this->isDir(index))
        {
            QDir dir(this->filePath(index));
            QFileInfoList files = dir.entryInfoList(QDir::NoDotAndDotDot | 
                                                    QDir::Files | QDir::Dirs);
            for(int file = 0; file < files.count(); file++)

                if(files.count()>0)
                    return QIcon(":/Icons/FullFolder.png");
            if(files.count()==0)
                return QIcon(":/Icons/EmptyFolder.png");

        }
        else{

            QFileInfo fi( this->filePath(index));
            QString ext = fi.suffix();

            if(ext=="jpeg"||ext=="jpg"||ext=="png"||ext=="bmp")
                return QIcon(filePath(index));
           }
    }

   if (role == Qt::CheckStateRole && !(this->filePath(parent)==""))
       return checklist.contains(index) ? Qt::Checked : Qt::Unchecked;
   return QFileSystemModel::data(index, role);

}

Qt::ItemFlags CustomModel::flags(const QModelIndex& index) const
{

    return QFileSystemModel::flags(index)| Qt::ItemIsUserCheckable;

}

bool CustomModel::setData(const QModelIndex& index, const QVariant& value, int role)
{

    if (role == Qt::CheckStateRole) {

        if (value == Qt::Checked)
            checklist.insert(index);
        else
            checklist.remove(index);

        emit dataChanged(index, index);
        return true;
    }
    return QFileSystemModel::setData(index, value, role);
}

1 个答案:

答案 0 :(得分:1)

不确定它是否相关,但我在下面的注释中找到了以下注释: http://doc.trolltech.com/4.6/qt.html#ItemFlag-enum

“请注意,需要为可检查项目提供一组合适的标志和初始状态,指示是否检查该项目。这是针对模型/视图组件自动处理的,但需要为实例明确设置QListWidgetItem,QTableWidgetItem和QTreeWidgetItem。“

据我所知,您的代码看起来是正确的 - 但是可能尝试在基本QFileSystemModel类(在您的自定义构造函数中)上设置ItemIsUserCheckable标志,并查看继承的data()和setData()方法是否有效with role = Qt :: CheckStateRole。如果由于其他原因需要维护当前检查的列表,那么继续在派生的setData()中执行此操作,但仍然可以调用QFileSystemModel :: setData()。

与此同时,我正在寻找为什么我的QTreeView在修改文件时不会更新时间戳(除非我退出并重新启动我的应用程序,有点挫败了目的!)...看起来像dataChanged()信号没有被释放。