Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

[SOLVED] Problem in moving QListWidget's Item either up or down by one position



  • HI all,
    I want to move the selected item from QListWidget either moving UP or Down by one position....by pressing separate
    PushButton..
    @
    void CTestDlg::UpButtonPressed()
    {
    int nCurRow = ui->listWdgt->currentRow();
    if( nCurRow== 0)
    return;

    QListWidgetItem *curItem = ui->listWdgt->currentItem();
    QListWidgetItem *prevItem = ui->listWdgt->item( nCurRow - 1 );

    ui->listWdgt->scrollToItem( curItem,QAbstractItemView::PositionAtTop );
    }

    void CTestDlg::downButtonPressed()
    {
    int nListCount = ui->listWdgt->count();
    int nCurRow = ui->listWdgt->currentRow();
    if( nListCount == nCurRow )
    return;

    QListWidgetItem *curItem =  ui->listWdgt->currentItem();
    QListWidgetItem *prevItem =  ui->listWdgt->item( nCurRow + 1 );
    
    ui->listWdgt->scrollToItem( curItem,QAbstractItemView::QAbstractItemView::PositionAtBottom );
    

    }
    @

    Please let me know whether i am doing anything wrong on this???



  • from Reference:
    @void QListWidget::scrollToItem ( const QListWidgetItem * item, QAbstractItemView::ScrollHint hint = EnsureVisible ) [slot]@

    bq. Scrolls the view if necessary to ensure that the item is visible.

    as I think you need change item position, not scroll to item.

    yo can do it with two methods:

    @QListWidgetItem * QListWidget::takeItem ( int row )@
    for extracting item from list
    and
    @void QListWidget::insertItem ( int row, QListWidgetItem * item )@
    for inserting to needed position.

    So.. You can get something like:

    @ QListWidgetItem *curItem = ui->listWdgt->takeItem(nCurRow);
    ui->listWdgt->insertItem( nCurRow + 1, curItem );@

    Note: Don't forget check limits.



  • [quote author="Vass" date="1317922866"]
    Note: Don't forget check limits.[/quote]

    And don't forget that count() is 1 based, and currentRow() is 0 based, i.e. the first row is #0, not #1. And the last row is count() - 1.



  • Thanks Vass and Volker...its working absolutely fine...

    Thanks for the valuable inputs..


Log in to reply