I want to create a Photoshop like GUI for layer selection and visibility to manage the layers for my software. Basically, I want to have something like a ListView
with the QListWidgetItem
having text for the layer and a check-box for visibility.
At first it seemed easy to do with QListWidget
and QListWidgetItem
by setting the flags of the item to make it UserCheckable. It works to some extent, but it forces me to select a 'layer' before I can change its visibility.
Is there some way to implement QListWidgetItem so that I can check/uncheck the check-box without having to select the item? Or should I try something else to implement my layer manager?
I am considering to do it with QGraphicsView
and QGraphicsItem
, but I'd really like to know if I can implement this without.
QListWidget uses itemAt( ) to determine a clicked items bounding rectangle and selects it - even when its only the checkbox. As this method is not virtual, you cannot change that behaviour without any dirty tricks (changing selection each time check boxes toggled etc). You would have to derive your own QListView and QAbstractItemModel (like QListWidget does). Dont worry, others noticed the some inconvinient check/selection behaviour. Let me give you some direction:
You should derive your own QAbstractItemModel which has two columns. The first columns is your checkbox column and you need to assign a column delegate which draws checkbox items, the second is your display text column (not covered below). Then in YourListView class:
Connect the clicked signal to your own slot:
connect( this, SIGNAL(clicked( const QModelIndex & )), this, SLOT(clickedSlot( const QModelIndex & )) );
and declare/use
void YourListView::clickedSlot( const QModelIndex &index )
{
if( index.isValid() )
{
// Checkbox toggle
if( index.column() == 0 )
{
QVariant beforeValue = this->model()->data( index );
this->model()->setData( index, QVariant::fromValue( ! beforeValue.toBool() ) );
}
else
if( index.column() == 1 )
{
this->selectionModel()->select( index, QItemSelectionModel::Toggle );
}
}
}
I know the Qt's model-view-delegate architecture is somewhat scary for the untrained programmer, but once understood its fun. Ah, I would personally refrain from using a hand-woven QGraphicsView solution - it has its own traps and corners which likely will cost you more time to get it into acceptable shape.
Good Luck!