Qtreeview, resizing a row when it is selected

I am using Qt 4.7.0, Qtreeview with multiple columns.

What I want to do is โ€œsimpleโ€: I want the row to increase the height when it was selected.

Will there be enough delegates for this?

I went through some things with QTableView:

m_pMyTableView->verticalHeader()->setResizeMode(QHeaderView::Interactive); ... QSize AbstractItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const; 

It works with this table view, but I donโ€™t see how I will do it in QTreeview, since for a start it does not have vertical headers ...

Can someone enlighten my path?

+4
source share
1 answer

Along with setting up uniformRowHeights in your QTreeView is what I would like to try.

There are several ways to do this, I like to use Qt signals / slots, so we will change the height using a custom QAbstractItemModel on a QTreeView . This custom model will be connected to the selectionChanged signal from the QItemSelectionModel your QTreeView . The sample code / snippets works with one selection mode, but you can easily change it to handle multiple selected lines.

Step 1 - Creating a Custom Model with a Selection Slot

Create your own model class, which comes from QAbstractItemModel and make sure you create a slot, for example:

 Q_SLOTS: void onSelectionChanged( const QItemSelection&, const QItemSelection& ); 

Inside the model class, add the following snippets / methods.

 void MyModelClass::onSelectionChanged( const QItemSelection& selected, const QItemSelection& deselected ) { if( !selected.empty() ) { // Save the index within the class. m_selectedIndex = selected.first(); Q_EMIT dataChanged( m_selectedIndex, m_selectedIndex ); } } QVariant MyModelClass::data( const QModelIndex& index, int role ) const { // Use the selected index received from the selection model. if( m_selectedIndex.isValid() && index == m_selectedIndex && role == Qt::SizeHintRole ) { // Return our custom size! return QSize( 50, 50 ); } ... } 

Step 2 - Connect the selection changes to your model

Inside the initialization of your QTreeView create your own model and do the following:

 MyTreeView::MyTreeView( QWidget* parent ) : QWidget( parent ) { ... MyModelClass* model = new MyModelClass(); setModel( model ); setSelectionMode( QAbstractItemView::SingleSelection ); setSelectionBehavior( QAbstractItemView::SelectRows ); connect ( selectionModel(), SIGNAL( selectionChanged(const QItemSelection&, const QItemSelection&) ), model, SLOT( onSelectionChanged(const QItemSelection&, const QItemSelection&) ) ); } 

I am sure there are several ways to do this, i.e. pass the QItemSelectionModel directly to your QAbstractItemModel , but again I prefer to use signals / slots and save the selection in the model.

Hope this helps.

+1
source

All Articles