簡體   English   中英

使用自定義模型的帶有復選框的qlistview

[英]qlistview with checkboxes using custom model

我有子類化的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

“請注意,必須給可檢查的項目同時提供一組合適的標志和初始狀態,以指示是否檢查了該項目。這是針對模型/視圖組件自動處理的,但需要為QListWidgetItem的實例進行顯式設置, QTableWidgetItem和QTreeWidgetItem。”

據我所知,您的代碼看起來正確-但也許可以嘗試在基本QFileSystemModel類上(在您的自定義構造函數中)設置ItemIsUserCheckable標志,並查看繼承的data()和setData()方法是否與role =一起使用Qt :: CheckStateRole。 如果您需要維護由於其他原因當前正在檢查的內容的列表,請繼續執行此操作,並在派​​生的setData()中執行此操作,但仍要調用QFileSystemModel :: setData()。

同時,我正在尋找為什么我在修改文件時QTreeView不更新時間戳(除非我退出並重新啟動我的應用程序,否則會破壞目的!)...看起來dataChanged()信號不是被發射。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM