Bienvenue sur le forum !

Si vous souhaitez rejoindre la communauté, cliquez sur l'un de ces boutons !

Qt 5 : 5.9.1 - Qt Creator : 4.4.0 - Qt Installer : 2.0.3 - JOM : 1.1.2 - Qt Build suite : 1.7.0 - VS Qt 5 : 2.0.0

Ajoutez des Checkbox à vos Modèles

Bonjour tout le monde.

Pour un besoin personnel, j'ai mis en place une classe héritant de QFileSystemModel, en rendant la première colonne Checkable.
Hors, premièrement ça ne me plaisait pas de mélanger ce comportement (ajout de checkbox) à celui de base (parcourt du système de fichiers), la transformant un peu trop en "super class".
Deuxièmement, je me suis dit que si pour un autre modèle je voulais aussi ajouter des checkbox, je devrais recommencer à zéro. Si je voulais ajouter un autre comportement en plus de rendre le modèle checkable, je devrais retravailler ma classe en profondeur.

Bref, ça ne me plaisait pas!

J'ai donc déporté toute cette partie dans un ProxyModel, histoire de rendre le tout modulable.
Premièrement, j'ai mis en place AbstractRoleProxyModel, pour mutualiser les tratements communs aux différentes classes de rôles (pour le moment, juste Checkable)
Ensuite j'ai porté ma partie Checkable dans un proxy héritant de AbstractRoleProxyModel

Je suis ouvert à toute remarque/conseil/correction avis :)


Place au code...



Headers

///
/// \file : AbstractRoleProxyModel.h
///
#ifndef ABSTRACTROLEPROXYMODEL_H
#define ABSTRACTROLEPROXYMODEL_H

#include <QIdentityProxyModel>
#include <QHash>
#include <QByteArray>

class AbstractRoleProxyModel : public QIdentityProxyModel
{
Q_OBJECT
public:
explicit AbstractRoleProxyModel(QObject *parent = 0);
virtual QHash<int, QByteArray> proxyRoleNames() const = 0;
QHash<int, QByteArray> roleNames() const;
signals:

public slots:

};

#endif // ABSTRACTROLEPROXYMODEL_H

///
/// \file : CheckableRoleProxyModel.cpp
///

///
/// CheckableRoleProxyModel: a Qt proxy model to add the checkable role
/// to your models
///
/// Copyright (C) 2013 Pascal Blétard <bletard.p@live.fr>
///
/// This program is free software: you can redistribute it and/or modify
/// it under the terms of the GNU General Public License as published by
/// the Free Software Foundation, either version 3 of the License, or
/// (at your option) any later version.
/// This program is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU General Public License for more details.
/// You should have received a copy of the GNU General Public License
/// along with this program. If not, see <http://www.gnu.org/licenses/>.
///
/// \date 06/08/2013
/// \version 0.1
/// \author Pascal Blétard
///

#ifndef CHECKABLEROLEPROXYMODEL_H
#define CHECKABLEROLEPROXYMODEL_H

#include "AbstractRoleProxyModel.h"
#include <QSet>
#include <QHash>
#include <QMap>
#include <QDebug>

class CheckableRoleProxyModel : public AbstractRoleProxyModel
{
Q_OBJECT



public:



CheckableRoleProxyModel(QObject *parent = 0);


///
/// \brief The Priority enum
///
/// \see checkablePriority()
/// \see setCheckablePriority()
///
enum Priority {
Indices, Columns, Rows
};


///
/// \brief Returns the item flags for the given index in the model.
///
/// The flags are an \c OR combination of this values:
/// \htmlonly
/// <table>
/// <tr><td>Qt::NoItemFlags </td><td> 0 </td><td> It does not have any properties set. </td></tr>
/// <tr><td>Qt::ItemIsSelectable </td><td> 1 </td><td> It can be selected. </td></tr>
/// <tr><td>Qt::ItemIsEditable </td><td> 2 </td><td> It can be edited. </td></tr>
/// <tr><td>Qt::ItemIsDragEnabled </td><td> 4 </td><td> It can be dragged. </td></tr>
/// <tr><td>Qt::ItemIsDropEnabled </td><td> 8 </td><td> It can be used as a drop target. </td></tr>
/// <tr><td>Qt::ItemIsUserCheckable </td><td> 16 </td><td> It can be checked or unchecked by the user. </td></tr>
/// <tr><td>Qt::ItemIsEnabled </td><td> 32 </td><td> The user can interact with the item. </td></tr>
/// <tr><td>Qt::ItemIsTristate </td><td> 64 </td><td> The item is checkable with three separate states. </td></tr>
/// <tr><td>Qt::ItemNeverHasChildren </td><td> 128 </td><td> The item never has child items. </td></tr>
/// </table>
/// \endhtmlonly
///
Qt::ItemFlags flags(const QModelIndex& index) const;



///
/// \brief Returns the data for the model item index with the given role
/// \param index
/// \param role
/// \return The requested data if successful; otherwise an invalid QVariant() empty data
///
QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;


///
/// \brief Sets the data for the model item index with the given role
/// to the data referenced by the value.
///
/// The dataChanged() signal should be emitted if the data was successfully set.
///
/// \param index
/// \param value
/// \param role
/// \return Returns true if successful; otherwise returns false.
///
bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole);



///
/// \brief Returns a map with values for all predefined roles in the model for the item at the given index.
/// \param index
/// \param role
/// \return All predefiened datas if successful; otherwise an invalid QVariant() empty data
///
QMap<int, QVariant> itemData(const QModelIndex& index) const;



// want to be implements? How it work...
//bool setItemData(const QModelIndex& index, const QMap<int, QVariant>& roles);



///
/// \brief Returns the proxies role names.
///
/// Returns a pairs list of Qt::ItemDataRole with their labels,
/// used in the proxy.
///
/// \return
///
QHash<int, QByteArray> proxyRoleNames() const;



///
/// \brief Retrieves if an index is checkable or not.
///
/// By default, class verifies first if index is checkable,
/// then if column is checkable and finally if row is checkable.
/// This behavior can be changed by use of setCheckablePriority()
///
/// \see checkablePriority()
/// \see setCheckablePriority()
/// \see indexCheckable()
/// \see columnCheckable()
/// \see rowCheckable()
/// \param index
/// \return
///
bool checkable(const QModelIndex& index) const;



///
/// \brief Retrieves if an index is checkable or not.
///
/// Only seek in parameters of index, regardless of settings of column or of row
///
/// \note To verify if an index is really Checkable, use checkable()
/// \see checkable()
/// \see setIndexCheckable()
/// \see columnCheckable()
/// \see rowCheckable()
/// \param index
/// \return Returns true if index is Checkable; otherwise returns false.
///
bool indexCheckable(const QModelIndex& index) const;



///
/// \brief Retrieves if the column of an index is checkable or not.
///
/// Only seek in parameters of the indice's column, regardless of settings of index or of row
///
/// \note To verify if an index is really Checkable, use checkable()
/// \see checkable()
/// \see setColumnCheckable()
/// \see indexCheckable()
/// \see rowCheckable()
/// \param index
/// \return Returns true if the indice's column is Checkable; otherwise returns false.
///
bool columnCheckable(const QModelIndex& index) const;



///
/// \brief Retrieves if the column is checkable or not.
///
/// Only seek in parameters of the column, regardless of settings of index or of row
///
/// \note To verify if an index is really Checkable, use checkable()
/// \see checkable()
/// \see setColumnCheckable()
/// \see indexCheckable()
/// \see rowCheckable()
/// \param index
/// \return Returns true if the column is Checkable; otherwise returns false.
///
inline bool columnCheckable(int column) const
{
return m_checkable_columns.value(column, false);
}



///
/// \brief Retrieves if the row of an index is checkable or not.
///
/// Only seek in parameters of the indice's row, regardless of settings of index or of column
///
/// \note In case of a tree type model,
/// all children's indices with this row's number are checkable.
/// \note To verify if an index is really Checkable, use checkable()
/// \see checkable()
/// \see setRowCheckable()
/// \see indexCheckable()
/// \see columnCheckable()
/// \param index
/// \return Returns true if the indice's row is Checkable; otherwise returns false.
///
bool rowCheckable(const QModelIndex& index) const;



///
/// \brief Retrieves if the row is checkable or not.
///
/// Only seek in parameters of the row, regardless of settings of index or of column
///
/// \note In case of a tree type model,
/// all children's indices with this row's number are checkable.
/// \note To verify if an index is really Checkable, use checkable()
/// \see checkable()
/// \see setRowCheckable()
/// \see indexCheckable()
/// \see columnCheckable()
/// \param index
/// \return Returns true if the row is Checkable; otherwise returns false.
///
inline bool rowCheckable(int row) const
{
return m_checkable_rows.value(row, false);
}


///
/// \brief Sets an precise index Checkable or not.
///
/// \see checkable()
/// \see indexCheckable()
/// \see setColumnCheckable()
/// \see setRowCheckable()
/// \param index The index sets to be Checkable
/// \param checkable Does the column is Checkable or not
/// \return Returns true if successful; otherwise returns false
///
bool setIndexCheckable(const QModelIndex& index, bool checkable = true, Qt::CheckState state = Qt::Unchecked);



///
/// \brief Sets column of an index Checkable or not.
///
/// \see checkable()
/// \see columnCheckable()
/// \see setIndexCheckable()
/// \see setRowCheckable()
/// \param index The index whose column is set to Checkable
/// \param checkable Does the column is Checkable or not
/// \return Returns true if successful; otherwise returns false
///
bool setColumnCheckable(const QModelIndex& index, bool checkable = true);



///
/// \brief Sets column Checkable or not.
///
/// \see checkable()
/// \see columnCheckable()
/// \see setIndexCheckable()
/// \see setRowCheckable()
/// \param column The number of the column to set Checkable
/// \param checkable Does the column is Checkable or not
/// \return Returns true if successful; otherwise returns false
///
bool setColumnCheckable(int column = 0, bool checkable = true);



///
/// \brief Sets row of an index Checkable or not.
///
/// \note In case of a tree type model,
/// all indices with the same row's number become checkable.
/// \see checkable()
/// \see rowCheckable()
/// \see setIndexCheckable()
/// \see setColumnCheckable()
/// \param index The index whose row is set to Checkable
/// \param checkable Does the row is Checkable or not
/// \return Returns true if successful; otherwise returns false
///
bool setRowCheckable(const QModelIndex& index, bool checkable = true);



///
/// \brief Sets row Checkable or not.
///
/// \note In case of a tree type model,
/// all indices with this row's number become checkable.
/// \see checkable()
/// \see rowCheckable()
/// \see setIndexCheckable()
/// \see setColumnCheckable()
/// \param row The number of the row to set Checkable
/// \param checkable Does the row is Checkable or not
/// \return Returns true if successful; otherwise returns false
///
bool setRowCheckable(int row, bool checkable = true);



///
/// \brief Returns the order of priorities used by the class
/// to see if an index is Checkable or not.
///
/// By default, class verifies first if index is checkable,
/// then if column is checkable and finally if row is checkable.
/// This behavior can be changed by use of setCheckablePriority()
///
/// \see Priority
/// \see setCheckablePriority()
/// \see checkable()
/// \return
///
inline QSet<Priority> checkablePriority() const
{
return m_priorities;
}



///
/// \brief Sets the order of priorities used by the class
/// to see if an index is Checkable or not.
///
/// By default, class verifies first if index is checkable,
/// then if column is checkable and finally if row is checkable.
/// This behavior can be changed by use of setCheckablePriority()
///
/// If a column was set as prioritary and is Checkable,
/// every indices of the column will be consid as Checkable
/// regardless of index/row settings.
///
/// \note You can't send twice the same Priority.
/// \see Priority
/// \see checkablePriority()
/// \see checkable()
/// \param first Priority The first to verify
/// \param second Priority Second to verify
/// \param third Priority Third and last to verify
/// \return Returns true if successful; otherwise returns false.
///
bool setCheckablePriority(Priority first,Priority second,Priority third);



///
/// \brief Sets the order of priorities used by the class
/// to see if an index is Checkable or not.
///
/// By default, class verifies first if index is checkable,
/// then if column is checkable and finally if row is checkable.
/// This behavior can be changed by use of setCheckablePriority()
///
/// If a column was set as prioritary and is Checkable,
/// every indices of the column will be consid as Checkable
/// regardless of index/row settings.
///
/// \note You can't send twice the same Priority.
/// \see Priority
/// \see checkablePriority()
/// \see checkable()
/// \param priorities \c QSet of the third priorities
/// \return Returns true if successful; otherwise returns false.
///
bool setCheckablePriority(QSet<Priority> priorities);



///
/// \brief Retrieves if Unchecked parents of the Checked indices
/// must be PartiallyChecked or not.
/// \note Only consistent with a tree type model
/// \return
///
inline bool partiallyCheckParents() const
{
return m_partially_check_parents;
}



///
/// \brief Sets if Unchecked parents of the Checked indices
/// must be PartiallyChecked or not.
/// \note Only consistent with a tree type model
/// \return
///
void setPartiallyCheckParents(bool partially_check_parents);



///
/// \brief Turns an index as checked
///
/// If \c partiallyCheckParents(true) was called,
/// parents are partially checked too if they aren't already checked.
///
/// \see partiallyCheckParents()
/// \see setPartiallyCheckParents()
/// \see uncheck()
/// \see toggleCheck()
/// \see checked()
/// \param index The\c QModelIndex of the item in the model to uncheck
/// \return Returns true if successful; otherwise returns false.
///
inline bool check(QModelIndex index)
{
return setData(index, Qt::Checked, Qt::CheckStateRole);
}



///
/// \brief Turns an index as unchecked
///
/// If \c partiallyCheckParents(true) was called, parents partially checked
/// who haven't another checked childs are unchecked too.
///
/// \see partiallyCheckParents()
/// \see setPartiallyCheckParents()
/// \see check()
/// \see toggleCheck()
/// \see checked()
/// \param index The\c QModelIndex of the item in the model to uncheck
/// \return Returns true if successful; otherwise returns false.
///
inline bool uncheck(QModelIndex index)
{
return setData(index, Qt::Unchecked, Qt::CheckStateRole);
}



///
/// Toggles an index between the checked and unchecked state
///
/// If the \c CheckableRoleProxyModel::_partiallyCheckParents flag is active,
/// parent's checked states follow rules explained for check() and uncheck().
///
/// \see partiallyCheckParents()
/// \see setPartiallyCheckParents()
/// \see check()
/// \see uncheck()
/// \see checked()
/// \param index The\c QModelIndex of the item in the model to toggle checked state.
/// \return Returns true if successful; otherwise returns false.
///
bool toggleCheck(QModelIndex index);



///
/// Retrieves the checked state of an index
///
/// \see check()
/// \see uncheck()
/// \see toggleCheck()
/// \param index The\c QModelIndex of the item in the model to retrieve checked state.
/// \return Returns true if is checked; otherwise returns false.
///
bool checked(QModelIndex index) const;




///
/// Returns a list with all checked indices
///
/// \return Returns a \c QSet<QModelIndex> filled with Checked indices;
/// otherwise if there is no index Checked an empty \c QSet<QModelIndex>
///
inline QSet<QModelIndex> checkedIndices()
{
return m_checked;
}



signals:



///
/// \brief This signal is emitted whenever the checked state has toggled.
///
/// \see checkStateChanged()
/// \see check()
/// \see uncheck()
/// \see toggleCheck()
/// \see checked()
/// \param index The toggled index
///
void checkStateChanged(const QModelIndex index);



///
/// \brief This signal is emitted whenever the checked state has toggled.
///
/// \see checkStateChanged()
/// \see check()
/// \see uncheck()
/// \see toggleCheck()
/// \see checked()
/// \param index QModelIndex The toggled index
/// \param state Qt::CheckState The new state
///
void checkStateChanged(const QModelIndex index, const int state);



private:



///
/// \internal Recursivly sets the PartiallyChecked state on parents when
/// an index was Checked.
///
/// This function is called only if partiallyCheckParents(true) was called
/// on a tree type model.
///
/// \see partiallyCheckParents()
/// \see setPartiallyCheckParents()
/// \see check()
/// \see toggleCheck
///
void _partiallyCheckParents(const QModelIndex index);



///
/// \internal Recursivly unsets the PartiallyChecked state on parents when
/// an index was Unchecked.
///
/// This function is called only if partiallyCheckParents(true) was called
/// on a tree type model.
///
/// \see partiallyCheckParents()
/// \see setPartiallyCheckParents()
/// \see check()
/// \see toggleCheck
///
void _partiallyUncheckParents(const QModelIndex index);



///
/// \internal Pairs of indices/booleans which define
/// if index is checkable or not.
///
QHash<QModelIndex, bool> m_checkable_index;

///
/// \internal Pairs of columns number/booleans which define
/// if column is checkable or not.
///
QHash<int, bool> m_checkable_columns;

///
/// \internal Pairs of rows number/booleans which define
/// if row is checkable or not.
///
/// In case of a tree type model, all children's indices
/// with this row's number become checkable.
///
QHash<int, bool> m_checkable_rows;

///
/// \internal A list of all checked indices (refers to the proxy).
///
QSet<QModelIndex> m_checked;

///
/// \internal A list of all partially checked indices.
///
/// Empty if partiallyCheckParents(true) wasn't called
/// or if Model isn't a tree type model.
///
QSet<QModelIndex> m_partially_checked;

///
/// \internal The priorities order for determine if a index is checkable or not.
///
QSet<Priority> m_priorities;

///
/// \internal Determines if unchecked parents must be partially checked
/// if they have some checked children.
///
bool m_partially_check_parents;
};

#endif // CHECKABLEROLEPROXYMODEL_H

Sources

///
/// \file : AbstractRoleProxyModel.cpp
///

#include "AbstractRoleProxyModel.h"

AbstractRoleProxyModel::AbstractRoleProxyModel(QObject *parent) :
QIdentityProxyModel(parent)
{
}

QHash<int, QByteArray> AbstractRoleProxyModel::roleNames() const
{
if (sourceModel()) {
QHash<int, QByteArray> source_role_names = sourceModel()->roleNames();
QHash<int, QByteArray> proxy_role_names = proxyRoleNames();

foreach (int role, proxy_role_names.keys()) {
source_role_names.insert(role, proxy_role_names[role]);
}
return source_role_names;
}
return proxyRoleNames();
}


///
/// \file : CheckableRoleProxyModel.cpp
///

#include "CheckableRoleProxyModel.h"


// ----------------------
// ---- Constructors ----
// ----------------------



CheckableRoleProxyModel::CheckableRoleProxyModel(QObject *parent) :
AbstractRoleProxyModel(parent)
{
m_priorities.insert(Indices);
m_priorities.insert(Columns);
m_priorities.insert(Rows);

m_partially_check_parents = false;
}



// ----------------------
// ---- Reimplements ----
// ----------------------



Qt::ItemFlags CheckableRoleProxyModel::
flags(const QModelIndex& index) const
{
if (!index.isValid()) {
return Qt::NoItemFlags;
}
QModelIndex source_index = mapToSource(index);
Qt::ItemFlags flag = sourceModel()->flags(source_index);

//set flag to have only first column checkable for the whole list
if (checkable(index)) {
flag |= Qt::ItemIsUserCheckable;
}
return flag;
}



QVariant CheckableRoleProxyModel::
data(const QModelIndex& index, int role) const
{
if (!index.isValid()) {
return QVariant();
}
QModelIndex source_index = mapToSource(index);
// If index is checkable
if (role == Qt::CheckStateRole && checkable(index)) {
// item checked only if we have stored its path
if (m_checked.contains(source_index)) {
return QVariant(Qt::Checked);
}
if (m_partially_check_parents && m_partially_checked.contains(source_index)) {
return QVariant(Qt::PartiallyChecked);
}
return QVariant(Qt::Unchecked);
}
return sourceModel()->data(source_index, role);
}



QMap<int, QVariant> CheckableRoleProxyModel::
itemData(const QModelIndex& index) const
{
QModelIndex source_index = mapToSource(index);
QMap<int, QVariant> map = sourceModel()->itemData(source_index);
QVariant index_data = data(index, Qt::CheckStateRole);
map.insert(Qt::CheckStateRole, index_data);
return map;
}



bool CheckableRoleProxyModel::
setData(const QModelIndex& index, const QVariant& value, int role)
{
if (!index.isValid()) {
return false;
}
QModelIndex source_index = mapToSource(index);
if (role == Qt::CheckStateRole && checkable(index)) {
switch(value.toInt()) {
// save checked paths
case Qt::Checked:
if (!m_checked.contains(source_index)) {
m_checked.insert(source_index);
}
if (m_partially_check_parents) {
_partiallyCheckParents(source_index);
}
break;

// remove unchecked paths
case Qt::Unchecked:
// current index is checked? Damned! Go die in hell!
if (m_checked.contains(source_index)) {
m_checked.remove(source_index);
}
//
if (m_partially_check_parents) {
_partiallyUncheckParents(source_index);
}
break;
}
emit checkStateChanged(source_index);
emit checkStateChanged(source_index, value.toInt());
QVector<int> roles;
roles.append(role);
emit dataChanged(index, index, roles);
return true;
}
return sourceModel()->setData(source_index, value, role);
}



QHash<int, QByteArray> CheckableRoleProxyModel::
proxyRoleNames() const
{
QHash<int, QByteArray> roles;
roles.insert(Qt::CheckStateRole, QByteArray("checkState"));
return roles;
}



// ------------------
// ---- Features ----
// ------------------

bool CheckableRoleProxyModel::
checkable(const QModelIndex& index) const
{
if (!index.isValid()) {
return false;
}
foreach(Priority priority, m_priorities) {
switch (priority) {
case Indices : {
if (m_checkable_index.contains(index)) {
return indexCheckable(index);
}
break;
}
case Columns : {
if (m_checkable_columns.contains(index.column())) {
return columnCheckable(index.column());
}
break;
}
case Rows : {
if (m_checkable_rows.contains(index.row())) {
return rowCheckable(index.row());
}
}
}
}
return false;
}



bool CheckableRoleProxyModel::
indexCheckable(const QModelIndex& index) const
{
if (!index.isValid()) {
return false;
}
return m_checkable_index.value(index, false);
}



bool CheckableRoleProxyModel::
columnCheckable(const QModelIndex& index) const
{
if (!index.isValid()) {
return false;
}
return columnCheckable(index.column());
}



bool CheckableRoleProxyModel::
rowCheckable(const QModelIndex& index) const
{
if (!index.isValid()) {
return false;
}
return rowCheckable(index.row());
}



bool CheckableRoleProxyModel::
setIndexCheckable(const QModelIndex& index, bool checkable, Qt::CheckState state)
{
if (!index.isValid()) {
return false;
}
m_checkable_index.insert(index, checkable);

if (state == Qt::Checked) {
check(index);
}
return true;
}



bool CheckableRoleProxyModel::
setColumnCheckable(const QModelIndex& index, bool checkable)
{
if (!index.isValid()) {
return false;
}
return setColumnCheckable(index.column(), checkable);
}



bool CheckableRoleProxyModel::
setColumnCheckable(int column, bool checkable)
{
if (column <0) {
return false;
}
m_checkable_columns.insert(column, checkable);
return true;
}



bool CheckableRoleProxyModel::
setRowCheckable(const QModelIndex& index, bool checkable)
{
if (!index.isValid()) {
return false;
}
return setRowCheckable(index.row(), checkable);
}



bool CheckableRoleProxyModel::
setRowCheckable(int row, bool checkable)
{
if (row < 0) {
return false;
}
m_checkable_rows.insert(row, checkable);
return true;
}



bool CheckableRoleProxyModel::
setCheckablePriority(Priority first,Priority second,Priority third)
{
QSet<Priority> priorities;
priorities.insert(first);
priorities.insert(second);
priorities.insert(third);
return setCheckablePriority(priorities);
}



bool CheckableRoleProxyModel::
setCheckablePriority(QSet<Priority> priorities)
{
if (priorities.size() == 3) {
m_priorities = priorities;
return true;
}
return false;
}



void CheckableRoleProxyModel::
setPartiallyCheckParents(bool partially_check_parents)
{
// only if setting have changed
if (m_partially_check_parents != partially_check_parents) {
m_partially_check_parents = partially_check_parents;
if (partially_check_parents) {
// partially check parents for each checked index
foreach(QModelIndex index, m_checked) {
_partiallyCheckParents(index);
}
}
else {
m_partially_checked.clear();
}
emit layoutChanged();
}
}



bool CheckableRoleProxyModel::
toggleCheck(const QModelIndex index)
{
if (checked(index)) {
return uncheck(index);
}
return check(index);
}



bool CheckableRoleProxyModel::
checked(const QModelIndex index) const
{
return (Qt::Checked == (Qt::CheckState)index.data(Qt::CheckStateRole).toInt());
}

// -------------------
// ----- Private -----
// -------------------


void CheckableRoleProxyModel::
_partiallyCheckParents(const QModelIndex index)
{
// source's parent exists?
QModelIndex source_parent = index.parent();
if (source_parent.isValid()) {

// if proxy parent index is checkable but not partially checked
QModelIndex proxy_parent = mapFromSource(source_parent);
bool partially_checked = m_partially_checked.contains(source_parent);

if (checkable(proxy_parent) && !partially_checked) {
// partially check parent and notify it
m_partially_checked.insert(source_parent);
emit dataChanged(proxy_parent, proxy_parent);
}
// if parent is checkable (or not), maybe his ancestors are
_partiallyCheckParents(source_parent);
}
}



void CheckableRoleProxyModel::
_partiallyUncheckParents(const QModelIndex index)
{
// source parent exists?
QModelIndex source_parent = index.parent();
if (source_parent.isValid()) {

// if proxy parent index is checkable and partially checked
QModelIndex proxy_parent = mapFromSource(source_parent);
bool partially_checked = m_partially_checked.contains(source_parent);

if (checkable(proxy_parent) && partially_checked) {
bool childChecked = false;
// check if parent have another checked childs
for (int i = 0; source_parent.child(i,0).isValid(); ++i) {
partially_checked = m_partially_checked.contains(source_parent.child(i,0));
bool checked = m_checked.contains(source_parent.child(i,0));
if(partially_checked || checked) {
childChecked = true;
break;
}
}
// If not, uncheck it
if (!childChecked) {
m_partially_checked.remove(source_parent);
emit dataChanged(proxy_parent, proxy_parent);
}
//todo: verify not after }
_partiallyUncheckParents(source_parent);

}
}
}

Exemple

///
/// \file : FileSystemModel.h
///

#ifndef FILESYSTEMMODEL_H
#define FILESYSTEMMODEL_H

#include <QFileSystemModel>

class FileSystemModel : public QFileSystemModel
{
Q_OBJECT
public:

///
/// Returns true if parent has any children or has the Qt::ItemNeverHasChildren flag set;
/// otherwise returns false.
///
/// Use rowCount() on the parent to find out the number of children.
///
/// \remarks Reimplemented to avoid empty directories to be collapsables
/// and to implement the \c Qt::ItemNeverHasChildren flag.
/// \see rowCount()
/// \see child()
///
///
bool hasChildren(const QModelIndex &parent) const;
};

#endif // FILESYSTEMMODEL_H


///
/// \file : Window.h
///

#ifndef WINDOW_H
#define WINDOW_H

#include <QWidget>
#include <QTreeView>
#include <QGridLayout>

#include "../src/FileSystemModel.h"
#include "../src/CheckableRoleProxyModel.h"

class Window : public QWidget
{
Q_OBJECT

public:
Window(QWidget *parent = 0);
};

#endif // WINDOW_H


///
/// \file : FileSystemModel.cpp
///

#include "FileSystemModel.h"

bool FileSystemModel::hasChildren(const QModelIndex &parent) const
{
// return false if item cant have children
if (parent.flags() & Qt::ItemNeverHasChildren) {
return false;
}
// return if at least one child exists
return QDirIterator(filePath(parent),
filter() | QDir::NoDotAndDotDot,
QDirIterator::NoIteratorFlags
).hasNext();
}


///
/// \file : Windowcpp
///

#include "Window.h"

Window::Window(QWidget *parent)
: QWidget(parent)
{
FileSystemModel* model = new FileSystemModel();
model->setRootPath("");

CheckableRoleProxyModel* checkable = new CheckableRoleProxyModel(this);
checkable->setColumnCheckable(0, true);
checkable->setPartiallyCheckParents(true);

checkable->setSourceModel(model);

QTreeView * m_dir = new QTreeView;
m_dir->setModel(checkable);

QGridLayout * layout = new QGridLayout;
layout->addWidget(m_dir, 0, 0, 6, 8);
setLayout(layout);
}


///
/// \file : main.cpp
///

#include "Window.h"
#include <QApplication>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Window w;
w.show();

return a.exec();
}

Réponses

  • August 2013 modifié
    Salut,

    Ton code est propre, spacieux, agréable à regarder =)

    Bon après moi j'aime pas trop quand y'a masse commentaires comme ça, mais c'est qu'un avis personnel, la plupart des gens préfèrent qu'il y en ai plus que pas assez, et puis faire une doc c'est cool ;)

    J'imagine que si tu as posté ton code ici et que tu as fait une doc c'est dans l'idée de partager tout ça. Est ce que ca serait pas mieux que tu fasse un .zip avec un mini projet d'exemple que tu mettrai à disposition en téléchargement sur le forum ?
    Ça éviterai le pavé de code qui rallonge la page :p
    A la limite laisse simplement le code de tes deux classes en réduisant un peu les espaces ;)
    Tu peux éditer ton premier poste si jamais tu change d'avis.

    Merci pour ton partage avec la communauté =)


    EDIT : Ah et puis j'ai failli passer a coter, ici il est coutume de se présenter pour connaitre un peu les gens, si tu veux bien passer par Le coin des membres ce serait fort aimable =)
  • Yep merci de ta réponse.

    Je suis conscient que avec les sources, la page fait 3km le long ^^
    Je vais voir si je peux placer tout cas, avec différents projets d'exemple dans un zip sur le ftp. (si je dispose toujours du miens :/ )

    Je compte dev d'autres RoleProxy (editable, ...), pour en faire un ensemble fonctionnel ;)
    Mais avant:
    1// je trouvais domage de laisser le code dormir sur mon PC alors qu'il pourrait déjà être utile en l'état

    2// j'aurais aimé avoir des avis/remarques sur le code (le fond et la forme), vu que cela fait longtemps que je n'avais plus programmé en c++, certaines pratiques se perdent.
    Il y a surement des choses à améliorer ;)

    Pour la présentation: c'est noté, j'y irai dès ce soir je pense :p
Connectez-vous ou Inscrivez-vous pour répondre.