Changing column order in a QTableView?
-
I have a QTableView that has a custom QSqlTableModel as the model. In the database, the columns are A, B, C, I want to display A, C, B. How do I do that? I tried this, but it didn't work:
@
QHeaderView * productTableHeaderView = ui.productTableView->horizontalHeader();
int priceVisualIdx = productTableHeaderView->sectionPosition(_priceListItemModel->priceNo());
int imageMaxVisualIdx = productTableHeaderView->sectionPosition(_priceListItemModel->imageMaxCntNo());
productTableHeaderView->swapSections (imageMaxVisualIdx, priceVisualIdx);
@Sam
[EDIT: fixed code formatting, please wrap in @-tags, Volker ]
-
Use a proxy model between your model and the view. To do this it looks like you may need to implement your own proxy since QSortFilterProxyModel sorts rows not columns.
So subclass QAbstractProxyModel and reimplement the mapToSource() and mapFromSource() functions to swap those two columns around.
-
I would use a much simpler approach, without any subclassing.
QTableView provides access to the header view via QTableView::horizontalHeader(). QHeaderView has a method called moveSection, that allows you to reorder the sections (in this case: columns) as you please. -
[quote author="Andre" date="1300615403"]I would use a much simpler approach, without any subclassing.
QTableView provides access to the header view via QTableView::horizontalHeader(). QHeaderView has a method called moveSection, that allows you to reorder the sections (in this case: columns) as you please.[/quote]
That's exactly what he's doing, so there's something else going on (wrong section numbers?)
-
[quote author="peppe" date="1300626770"]
[quote author="Andre" date="1300615403"]I would use a much simpler approach, without any subclassing.
QTableView provides access to the header view via QTableView::horizontalHeader(). QHeaderView has a method called moveSection, that allows you to reorder the sections (in this case: columns) as you please.[/quote]
That's exactly what he's doing, so there's something else going on (wrong section numbers?)[/quote]
Not exactly, but close, you're right. scarleton, could you insert some debug statement to see the actual values of the sections you're trying to swap?
André
-
Well, I added extracted the values:
@productTableHeaderView->setMovable(true);
int priceVisualIdx = productTableHeaderView->sectionPosition(_priceListItemModel->priceNo());
int imageMaxVisualIdx = productTableHeaderView->sectionPosition(_priceListItemModel->imageMaxCntNo());
qDebug("priceVisualIdx: %d imageMaxVisualIdx: %d", priceVisualIdx, imageMaxVisualIdx);
productTableHeaderView->swapSections (imageMaxVisualIdx, priceVisualIdx);@priceVisualIdx: 100 imageMaxVisualIdx: 300
-
So, it's likely that those values are actually the position in pixels of those sections. If
@
_priceListItemModel->priceNo()
_priceListItemModel->imageMaxCntNo()
@
are correct (i.e. they return the logical column index), you can pass them directly to swapSections.