File indexing completed on 2024-04-28 08:42:26

0001 /* 
0002     SPDX-FileCopyrightText: 2011 Michal Malek <michalm@jabster.pl>
0003     SPDX-FileCopyrightText: 1998-2007 Sebastian Trueg <trueg@k3b.org>
0004 
0005     SPDX-License-Identifier: GPL-2.0-or-later
0006 */
0007 
0008 #include "k3bmodelutils.h"
0009 #include <QModelIndex>
0010 
0011 namespace K3b
0012 {
0013 namespace ModelUtils
0014 {
0015     
0016     Qt::CheckState commonCheckState( const QModelIndexList& indexes )
0017     {
0018         int checked = 0;
0019         foreach( const QModelIndex& index, indexes ) {
0020             if ( index.data( Qt::CheckStateRole ).toInt() == Qt::Checked ) {
0021                 ++checked;
0022             }
0023         }
0024         
0025         if ( checked == 0 )
0026             return Qt::Unchecked;
0027         else if( checked == indexes.count() )
0028             return Qt::Checked;
0029         else
0030             return Qt::PartiallyChecked;
0031     }
0032     
0033     void toggleCommonCheckState( QAbstractItemModel* model, const QModelIndexList& indexes )
0034     {
0035         if ( model != 0 ) {
0036             Qt::CheckState commonState = commonCheckState( indexes );
0037             if ( commonState == Qt::Checked )
0038                 commonState = Qt::Unchecked;
0039             else
0040                 commonState = Qt::Checked;
0041             
0042             foreach( const QModelIndex& index, indexes ) {
0043                 model->setData( index, commonState, Qt::CheckStateRole );
0044             }
0045         }
0046     }
0047     
0048     QString commonText( const QModelIndexList& indexes, int role )
0049     {
0050         if ( !indexes.isEmpty() ) {
0051             QString firstData = indexes.first().data( role ).toString();
0052             for ( int i = 1; i < indexes.size(); ++i ) {
0053                 if ( indexes[i].data( role ).toString() != firstData )
0054                     return QString();
0055             }
0056             return firstData;
0057         }
0058         return QString();
0059     }
0060     
0061     void setCommonText( QAbstractItemModel* model, const QModelIndexList& indexes, const QString& value, int role )
0062     {
0063         if ( model != 0 ) {
0064             Q_FOREACH( QModelIndex index, indexes ) {
0065                 if( !value.isEmpty() || indexes.size() == 1 )
0066                     model->setData( index, value, role );
0067             }
0068         }
0069     }
0070     
0071 } // namespace ModelUtils
0072 } // namespace K3b