PDA

View Full Version : QTableWidget move row?


whitefurrows
22nd August 2006, 17:11
Hi,

i have a QTablewidget with "SingleSelection". How can i move the rows up and down?

Thanks in advance,

Whitefurrows

jpn
22nd August 2006, 22:26
There isn't any single API method for doing that. Use QTableWidget::takeItem() to temporarily remove both "source" and "destination" items from the table without deleting them, and then use QTableWidget::setItem() to set them back in a reverse order.

whitefurrows
23rd August 2006, 10:20
Hi,

the problem is i have many items in a row. I try this to remove the row.

QModelIndexList idxList = tableWidget->selectionModel()->selectedIndexes();

QListIterator<QModelIndex> idxIt(indexList);
idxIt.toBack();

while(idxIt.hasPrevious()){
QModelIndex idx = idxIt.previous();
if(index.column() == 0){
tableWidget->removeRow(idx.row());
}
}

but im not sure how can i paste it to move up and down. Can you help me please?

Thanks in advance,

Whitefurrows

jpn
23rd August 2006, 11:50
void TableWidget::move(bool up)
{
Q_ASSERT(selectedItems().count() > 0);
const int sourceRow = row(selectedItems().at(0));
const int destRow = (up ? sourceRow-1 : sourceRow+1);
Q_ASSERT(destRow >= 0 && destRow < rowCount());

// take whole rows
QList<QTableWidgetItem*> sourceItems = takeRow(sourceRow);
QList<QTableWidgetItem*> destItems = takeRow(destRow);

// set back in reverse order
setRow(sourceRow, destItems);
setRow(destRow, sourceItems);
}

// takes and returns the whole row
QList<QTableWidgetItem*> TableWidget::takeRow(int row)
{
QList<QTableWidgetItem*> rowItems;
for (int col = 0; col < columnCount(); ++col)
{
rowItems << takeItem(row, col);
}
return rowItems;
}

// sets the whole row
void TableWidget::setRow(int row, const QList<QTableWidgetItem*>& rowItems)
{
for (int col = 0; col < columnCount(); ++col)
{
setItem(row, col, rowItems.at(col));
}
}

whitefurrows
23rd August 2006, 13:47
Hi,

thank you for that great example, that's work fine.

Greetings,

Whitefurrows

roleroz
24th August 2006, 21:12
I have the same problem, but what i need to swap are the cell widgets, and getting the items don't work, the items get changed, but the cell widgets keep the same.

Is there any way of doing this?


QTableWidgetItem *item1 = colorizerTable->takeItem(row1, 0);
QTableWidgetItem *item2 = colorizerTable->takeItem(row2, 0);
colorizerTable->setItem(row1, 0, item2);
colorizerTable->setItem(row2, 0, item1);

jpn
24th August 2006, 21:17
Apparently QTableWidget::setCellWidget() maps the widget to the specific cell, not to the specific item. So you will have swap the cell widget by hand, too.

roleroz
24th August 2006, 21:23
The problem is that, when i set a widget for a specific cell, it deletes the previous one, so I cannot

The only way I've found is to have a Clone function in the widget's class