我将 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);
}
最佳答案
不确定它是否相关,但我在以下位置找到了以下注释: http://doc.trolltech.com/4.6/qt.html#ItemFlag-enum
Note that checkable items need to be given both a suitable set of flags and an initial state, indicating whether the item is checked or not. This is handled automatically for model/view components, but needs to be explicitly set for instances of QListWidgetItem, QTableWidgetItem, and QTreeWidgetItem.
据我所知,您的代码看起来是正确的——但也许可以尝试在 QFileSystemModel
基类(在您的自定义构造函数中)上设置 ItemIsUserCheckable
标志,并查看继承的 data() 和 setData()
方法是否适用于 role=Qt::CheckStateRole
。
如果出于某些其他原因需要维护当前检查内容的列表,请继续在派生的 setData()
中执行此操作,但仍调用 QFileSystemModel::setData( )
也是如此。
关于c++ - 带有使用自定义模型的复选框的qlistview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5347871/