-1

I have a tab which contains a QtableView and few buttons like "MOVE UP" and "MOVE DOWN". So on "MOVE UP" button press I have to move the entire row of QTableView one step up and the bring the adjacent one, one step down. I want to achieve this without creating complete model again since it may take time to construct the whole model again. Instead I just want to MOVE UP the selected row in the view. Please let me know the simplest way to achieve this.

Thanks in advance

Angie Quijano
  • 4,167
  • 3
  • 25
  • 30
Garifield
  • 63
  • 2
  • 8

2 Answers2

0

You don't need any knowledge of the model to do any of this, and most of the commenters are quite mistaken with any mention of the model at all.

You simply need to obtain the view's verticalHeader, and do a section swap of the item you want with the one above it. You might need to tell the verticalHeader to allow for reordering setMovable(true)

One of the main tenants QT and ModelView programming is to understand and appreciate the separation of manipulating a model from manipulating a view of the model.

UpAndAdam
  • 4,515
  • 3
  • 28
  • 46
0

I made the move up and down functions and this is what my .cpp contains

Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);

model = new QStandardItemModel(4,2,this);
for(int row = 0; row < 4; row++)
    {
        for(int col = 0; col < 2; col++)
        {
            QModelIndex index
                    = model->index(row,col,QModelIndex());
            // 0 for all data
            model->setData(index,row);
        }
    }
ui->tableView->setModel(model);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_upPushButton_clicked()
{
    if(ui->tableView->currentIndex().row()<=0)
    {
        return;
    }
    QList<QStandardItem *> list = model->takeRow(ui->tableView->currentIndex().row());
    model->insertRow(ui->tableView->currentIndex().row(),list);
}

void Widget::on_downPushButton_clicked()
{

int selectedRow = ui->tableView->currentIndex().row() ;
if(selectedRow == ui->tableView->model()->rowCount()-1)
{
   return;
}
QList<QStandardItem *> list = model->takeRow(ui->tableView->currentIndex().row());
model->insertRow(selectedRow+1,list);
}

This is what the ui looks like

Alex Pappas
  • 2,377
  • 3
  • 24
  • 48