PDA

View Full Version : QListView resize icon dynamically



Alundra
18th June 2014, 19:39
Hi all,
I want to resize icon dynamically when the view resize.
Here the actual code who works :


virtual void resizeEvent( QResizeEvent* e )
{
QFileSystemModel* Model = static_cast< QFileSystemModel* >( model() );
QDir RootDir = QDir( Model->filePath( rootIndex() ) );
RootDir.setFilter( Model->filter() );
RootDir.setNameFilters( Model->nameFilters() );
RootDir.refresh();
const int ItemSize = 128 + 16;
const int ItemRow = std::ceil( (float)e->size().width() / (float)ItemSize );
if( ItemRow > (int)RootDir.count() )
{
setIconSize( QSize( 128, 128 ) );
}
else
{
if( ItemRow > 0 )
{
const int SizeOffset = ( ItemSize - ( e->size().width() % ItemSize ) ) / ItemRow;
const int IconSize = ( 128 - SizeOffset <= 0 ) ? 128 : 128 - SizeOffset;
setIconSize( QSize( IconSize, IconSize ) );
}
else
{
setIconSize( QSize( 32, 32 ) );
}
}
QListView::resizeEvent( e );
}

Can it be better ? One flickering can be seen who is not good.
This flickering is because I only set icon 128x128 or it's problem of the code ?
The max icon size is 128x128 and I add 16 to have it correct about margin :


const int ItemSize = 128 + 16;

Can the item size can be computed by code without hard coded values ?
Thanks for the help

d_stranz
24th June 2014, 02:38
Can it be better ? One flickering can be seen who is not good.

The flickering is probably occurring because your implementation of resizeEvent() results in repainting the entire QListView for every mouse movement. If you can wait to redraw the view with new icon sizes until *after* the user has finished resizing, then one way to do it is like this:

- Add a one-shot QTimer instance to your listview class. Connect a slot to the timeout() signal. In that slot, do all the things you are now doing in the resize event.

- When the resizeEvent() is entered for the first time, start the timer with a short timeout (250 or 500 ms)
- On each resize event, check to see if the timer is running. If it is, stop it and restart it. Don't do anything else in the event (except maybe call the base class resizeEvent).

So, the way this will work is that nothing will happen to repaint the view with different icons until after the user has stopped moving the mouse (and the QTimer times out). When the QTimer fires, the view will be redrawn once with the new icons. If you are updating many icons, then you should call updatedEnabled( false) on your list view before starting the changes, then call updatesEnabled( true ) after you are all done.