PDA

View Full Version : copy selected rows from QTableView to another table



Sashabn
20th February 2015, 19:17
Can u help me with this. I try to copy selected data from one QTableView to another tableview, but when i run this code my program crash.
Can u help me with this?
void Dialog::on_pushButton_clicked()
{

QAbstractItemModel * model = ui->tableView->model();
QItemSelectionModel * selection = ui->tableView->selectionModel();
QModelIndexList indexes = selection->selectedIndexes();


if(!indexes.isEmpty()){


foreach (QModelIndex i, indexes) {


qDebug()<<i.row();
qDebug()<<i.column();
ui->tableView_2->model()->setData(ui->tableView_2->model()->index(i.row(),i.column()),ui->tableView->model()->data(i).toString());

}
}
}

d_stranz
21st February 2015, 00:06
As I count it, you have 8 or 9 pointers being retrieved or used in one method call or another, and not one of them is ever checked to see if it is actually a valid pointer. Nor do you ever check to see if the model indexes you are throwing around are valid. Who knows where it could be failing? Your code certainly doesn't.

Sashabn
21st February 2015, 07:01
Hi, problem is that i dont set model for second table, and that is the reason why my programs crash.
On first table i use QSqlQueryModel.
I need help to make an a empty table and when i click button to copy data selection from one table to another.
I know how to copy selection data from table, i dont know how to make empty table with model who store data in ram memory.
Sorry i am big noob and beginner. This is my 37 day of learning c++ and qt......
Thanks for any help...

d_stranz
24th February 2015, 00:04
Use QStandardItemModel as the model for your second table. For each item on the list of selected items, create a QStandardItem using the string retrieved from the selected item using its QModelIndex::data() method. Insert this new QStandardItem into the model at the appropriate place. If you assign the QStandardItemModel to your second table view, the view will automatically update as the model is changed.

You will have to decide whether you want to clear the second model with each new copy and paste, or whether new items are added to the end of the model.